Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...