Getting Uncaught TypeError: Cannot set property '0' of undefined error
Getting Uncaught TypeError: Cannot set property '0' of undefined error
我正在尝试为 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");
您需要将 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");
您的 obj
对象中没有 属性 newArray
。
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");
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 中的字数创建一个算法,我正在创建一个 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");
您需要将 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");
您的 obj
对象中没有 属性 newArray
。
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");
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");