user2925800
user2925800

Reputation: 103

CodeAcademy: Loops and Arrays 2, 12/14

I'm currently on the above excercise ^. I've basically got to try and get the five names printed out along with the string in the console.log below and for some reason I can't get this to work at all:

var names = ["Tobias", "Jehovah", "Jake", "Joseph", "Damn"];
for (var i = 0; i < names.length; i ++) {
    console.log("I know someone called " + [i])
}

Instead of printing out the names it prints out "I know someone called 1." I know this is really simple and I'm going to feel an idiot for it but I appreciate any help.

Upvotes: 1

Views: 3178

Answers (7)

Felipe Frotte
Felipe Frotte

Reputation: 1

You forget the space between called and the name. This should work:

var names = ["name1","name2","name3","name4","name5"];

for (var i = 0; i < names.length; i ++) {
console.log("I know someone called"+" "+names[i]);
}

=)

Upvotes: 0

sabrams
sabrams

Reputation: 1128

You're printing out [i] when you should be printing out names[i].

var names = ["Tobias", "Jehovah", "Jake", "Joseph", "Damn"];
for (var i = 0; i < names.length; i ++) {
    console.log("I know someone called " + names[i])
}

Upvotes: 0

ksu
ksu

Reputation: 608

i is just an increasing number.

var names = ["Tobias", "Jehovah", "Jake", "Joseph", "Damn"];
for (var i = 0; i < names.length; i ++) {
    console.log("I know someone called " + names[i])
 }

should do

Your for - loop has no chance to get to the names. with your variable names[i], you are accessing the i-th element of the names array.

Upvotes: 0

notArefill
notArefill

Reputation: 814

var names = ["Tobias", "Jehovah", "Jake", "Joseph", "Damn"];
for (var i = 0; i < names.length; i ++) {
    console.log("I know someone called " + names[i])
}

Upvotes: 2

Corbin
Corbin

Reputation: 33457

[i] is an array literal of an array that contains one item. To access an array (or object property), you use the [n] syntax, but you do it after the object name: names[i].

Upvotes: 0

Fabien Sa
Fabien Sa

Reputation: 9480

Use the names array.

var names = ["Tobias", "Jehovah", "Jake", "Joseph", "Damn"];
for (var i = 0; i < names.length; i ++) {
    console.log("I know someone called " + names[i])
}

Some informations about array: http://www.w3schools.com/js/js_obj_array.asp

Upvotes: 0

tymeJV
tymeJV

Reputation: 104785

Reference the array

names[i]

i is the index inside the for loop, so you put the array variable name, followed by the index to get the name at that index.

Upvotes: 0

Related Questions