我正在尝试为JavaScript中的单词计数创建算法,我正在创建一个for-in循环以从数组中获取每个单词,然后将其推入对象,但是在为每个数组设置每个对象键时却出错值。
const wordCount = input => {
let newArr = input.split(" ");
let obj = {};
for (let i in newArr) {
console.log(newArr[i]); // This returns value
obj.newArr[i] = 1; // This gives error:- Uncaught TypeError: Cannot set property '0' of undefined
}
console.log(obj);
};
wordCount("heyy how you doin heyy");
答案 0 :(得分:1)
您需要将newArr
初始化为obj
中的字段:
const wordCount = input => {
let newArr = input.split(" ");
let obj = { newArr: [] };
for (let i in newArr) {
console.log(newArr[i]); // This returns value
obj.newArr[i] = 1; // This gives error:- Uncaught TypeError: Cannot set property '0' of undefined
}
console.log(obj);
};
wordCount("heyy how you doin heyy");
答案 1 :(得分:1)
您的newArray
对象中没有属性obj
。
const wordCount = input => {
let newArr = input.split(" ");
let obj = {newArr: []};
for (let i in newArr) {
console.log(newArr[i]); // This returns value
obj.newArr[i] = 1; // This gives error:- Uncaught TypeError: Cannot set property '0' of undefined
}
console.log(obj);
};
wordCount("heyy how you doin heyy");
答案 2 :(得分:1)
const wordCount = input => {
let newArr = input.split(" ");
let obj = {};
for (let i in newArr) {
// console.log(newArr[i]); // This returns value
obj[newArr[i]] = 1; // This gives error:- Uncaught TypeError: Cannot set property '0' of undefined
}
console.log(obj);
};
wordCount("heyy how you doin heyy");