1

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

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));

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah but why does it work when you type it out like that? It seems like all I did was just access the index directly at first. Is that why the console.log method gave me numerical values instead of a string?
@KennethMcAusland Because 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.
0

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

0
for (i = 0; i < stuff.length; i++)   
 console.log(stuff[i]);

cheers :)

3 Comments

Quick explanation on why that works. I get that I'm accessing a method and that the i is the index pointing it out one by one... That said though, if someone could explain why typing it like that works... it'll help me understand it a bunch.
stuff is an Array containing strings. You "loop through them" and print them ;)
Trivaxy is wrong saying that for (i in stuff) works like that. "i" is a key in stuff array not a value.
0
for (i = 0; i < stuff.length; i++) {
    console.log(stuff[i]);
};

that will work for you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.