用 JavaScript 編寫從字串構建物件的程式碼


我們需要編寫一個函式,它需要將一個字串作為第一個且唯一的引數,並基於字串的唯一字元構建一個物件,每個鍵的預設值為 0。

例如:如果輸入字串是 -

const str = 'hello world!';

輸出

那麼輸出物件應該是 -

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 }

更新於: 2020 年 10 月 17 日

170 次檢視

開啟你的職業之旅

完成課程後獲得認證

開始入門
廣告
© . All rights reserved.