เราจำเป็นต้องเขียนฟังก์ชันที่รับสตริงเป็นอาร์กิวเมนต์แรกและอาร์กิวเมนต์เดียว และสร้างอ็อบเจ็กต์ด้วยคีย์ตามอักขระเฉพาะของสตริงและค่าของคีย์แต่ละคีย์ที่มีค่าเริ่มต้นเป็น 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 }