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 }
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP