捕获TypeError:无法设置未定义错误的属性“ 0”

时间:2019-11-24 16:15:06

标签: javascript arrays object word-count

我正在尝试为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 个答案:

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