Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

javascript - for loop undefined 'error'

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 - 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]);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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']

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...