开发者问题收集

获得未捕获的类型错误:无法设置未定义错误的属性‘0’

2019-11-24
450

我正在尝试在 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");
3个回答
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");
Kevin.a
2019-11-24

您需要将 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");
mickl
2019-11-24

您的 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");
Nicolas
2019-11-24