gpt4 book ai didi

javascript - 未捕获类型错误 : Cannot set property '0' of undefined error

转载 作者:行者123 更新时间:2023-11-28 16:56:28 25 4
gpt4 key购买 nike

我正在尝试在 JavaScript 中创建字数统计算法,我正在创建一个 for-in 循环来从数组中获取每个单词,然后将它们推送到对象,但在为每个数组设置每个对象键时出现错误值(value)。

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");

最佳答案

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");

关于javascript - 未捕获类型错误 : Cannot set property '0' of undefined error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59019719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com