用 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 }
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP