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

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

问题描述

我想做的是让空数组在 for 循环中记录年数组.岁月显示得很好,但我在控制台的末尾不断收到 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,你从索引开始到 0array 的长度 一一.让我们假设

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天全站免登陆