Pretty dumb question to ask and clearly shows I'm just getting started but I do have some trouble with this. Here's the array I'm dealing with:
var stuff = ["ken", "kenneth", "kenny", "kennayyy"];
Now here's the for loop I'm using:
for (i = 0; i < stuff.length; i++) {
console.log(i);
};
All I get in my chrome developer console is 0, 1, 2, 3.
How do I get each string value to show up?
4 Answers 4
You have to use i as a index of each value inside the stuff array to log it in the console.
var stuff = ["ken", "kenneth", "kenny", "kennayyy"];
for (i = 0; i < stuff.length; i++) {
console.log(stuff[i]);
};
Or just use Array#forEach instead of for loop.
var stuff = ["ken", "kenneth", "kenny", "kennayyy"];
stuff.forEach(v => console.log(v));
2 Comments
i is a numeric variable, as you can see it holds 0 when the loop starts and incrementing with every cycle of the loop, that's why you are getting only the numeric values. They are not connected with the array in any way, but if you change it into stuff[i] then it returns you the specified element from the stuff array on i position.You'll have to create a loop to access all members in the array. For simple purposes, either:
for(i = 0; i < stuff.length; i++)
{
console.log(stuff[i]);
}
Or you can directly have the value using a for..in loop
for(i in stuff)
{
console.log(i);
}
Both methods will produce the same output as all of the elements of the array are set to a value.
There are many methods to loop over an array in JavaScript and each of them has its advantages and disadvantages.
Comments
for (i = 0; i < stuff.length; i++)
console.log(stuff[i]);
cheers :)
3 Comments
for (i = 0; i < stuff.length; i++) {
console.log(stuff[i]);
};
that will work for you