for循环未定义的“错误" [英] for loop undefined 'error'

查看:95
本文介绍了for循环未定义的“错误"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是让空数组在for循环中记录Years-array.这些年表现得非常好,但是在控制台末尾,我总是得到 undefined .有人可以向我解释为什么会这样吗?

What I'm trying to do is make the empty array log the years-array in a for loop. The years are showing up perfectly fine, but I keep getting undefined at the end of the console. Can someone please explain to me why this is happening?

P.S-这里是自学成才的开发人员,请多多包涵,谢谢!

P.S - Self-taught developer here so please bear with me, thank you!

var empty = [];

var years = [1996, 1997, 2001, 1975, 1943];

for(var empty = 0; empty <= years.length; empty++) {
    console.log(years[empty]);
}

推荐答案

一个 array ,其中您从索引到 0 开始,一直到 array的长度一对一.让我们假设

An array where you are starting from index to 0 and going upto array's length one by one. Let us suppose

var arr = ['a', 'b', 'c', 'd', 'e']

现在,此 array 包含 5个元素.好吧,如果您从 0 开始对其进行计数,则您的第五元素索引 4 .但是在您的 loop 中,当索引为5时就将其断开.由于 index 5 上没有任何元素,您会得到未定义的错误.

Now this array contains 5 elements. Well, if you start counting it from 0, your fifth element index is 4. But in your loop you are breaking it when the index is 5. As there is no element on index 5 you are getting error undefined.

解决方案在检查索引是否为< = 的地方,将其替换为< ,因为当循环索引达到等于数组中元素总数为5时,它会中断并退出.

solution Where you check if index is <= replace that with < as when the loop index reaches equals to the total number element in your array which is 5 it get break and exit.

这篇关于for循环未定义的“错误"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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