为什么会出现TypeError:array [i]未定义? [英] Why am I getting TypeError: array[i] is undefined?

查看:57
本文介绍了为什么会出现TypeError:array [i]未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So in my program, I have an array that contains a dictionary/hash of values and when I loop through the array, I get the value I need but any code after the for loop does not get executed because the console outputs:

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循环下面执行代码.有谁知道为什么会发生这种情况以及我应该怎么解决?

I don't understand why this happens and I need the code underneath the for loop to execute. Does anyone know why this happens and what I should do to fix it?

推荐答案

问题

  1. 您尚未附带第一个 console.log 函数.
  2. 由于数组的索引为零,因此条件小于或等于将使循环尝试使用数组的 undefined 部分(大于总长度).因此,请使用小于运算符.
  1. You haven't enclosed your first console.log function.
  2. As an array is zero indexed making your condition less than or equal to will make the loop try to use an undefined part of the array (bigger than total length). Therefore use the less than operator.

固定代码

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

这篇关于为什么会出现TypeError:array [i]未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆