JavaScript 中透過字串構造 Form 物件


我們需要編寫一個函式,該函式以一個字串為第一個也是惟一引數,並根據字串的唯一字元構造一個物件,且每個鍵的值都預設為 0。

例如 −

// if the input string is:
const str = 'hello world!';
// then the output should be:
const obj = {"h": 0, "e": 0, "l": 0, "o": 0, " ": 0, "w": 0, "r": 0, "d": 0, "!": 0};

所以,讓我們編寫此函式的程式碼 −

示例

const str = 'hello world!';
const stringToObject = str => {
   return str.split("").reduce((acc, val) => {
      acc[val] = 0;
      return acc;
   }, {});
};
console.log(stringToObject(str));
console.log(stringToObject('is it an object'));

輸出

控制檯中的輸出如下 −

{ h: 0, e: 0, l: 0, o: 0, ' ': 0, w: 0, r: 0, d: 0, '!': 0 }
{ i: 0, s: 0, ' ': 0, t: 0, a: 0, n: 0, o: 0, b: 0, j: 0, e: 0, c: 0 }

更新於: 25-8-2020

227 次瀏覽

開始你的 職業

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.