【问题标题】:Why am I getting TypeError: array[i] is undefined? [duplicate]为什么我收到 TypeError: array[i] is undefined? [复制]
【发布时间】:2018-04-08 22:20:46
【问题描述】:

所以在我的程序中,我有一个包含值的字典/哈希值的数组,当我遍历数组时,我得到了我需要的值,但是 for 循环之后的任何代码都不会被执行,因为控制台输出:

TypeError: array[i] is undefined


var array = [
  {"name": "a", "pos": "C"},
  {"name": "b", "pos": "B"},
  {"name": "c", "pos": "W"},
];


for(var i = 0; i <= array.length; i++) {
  console.log(array[i]['pos'];
}
console.log("some other code");

我不明白为什么会发生这种情况,我需要执行 for 循环下面的代码。有谁知道为什么会发生这种情况以及我应该做些什么来解决它?

【问题讨论】:

  • 应该是&lt; array.length,而不是&lt;=
  • ^^^ 还有:在console.log(array[i]['pos']; 中缺少)

标签: javascript arrays loops for-loop console


【解决方案1】:

问题

  1. 您尚未封装您的第一个console.log 函数。
  2. 由于数组索引为零,因此您的条件less than or equal to 将使循环尝试使用数组的undefined 部分(大于总长度)。因此使用less than 运算符。

固定代码

var array = [
  {"name": "a", "pos": "C"},
  {"name": "b", "pos": "B"},
  {"name": "c", "pos": "W"},
];


for(var i = 0; i < array.length; i++) {
  console.log(array[i]['pos']);
}

console.log("some other code");

【讨论】:

    猜你喜欢
    • 2015-08-10
    • 1970-01-01
    • 2019-01-15
    • 2016-11-17
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2018-07-19
    • 2019-01-11
    相关资源
    最近更新 更多