Reputation: 286
I'm a beginner and have also had my head in Ruby for a bit, so I'm probably missing something small here.
But I'm curious why console.log(atheletes[i].win); is being skipped over for each iteration of [i]? I've discovered that by the time the counter reaches that point, it's already to 2, so it returns undefined because it's past the end of the array.
What's weird is if I change the semicolon from the statement before it into a comma, it works. So for some reason the iterator is only working for the first statement.
var tim = {
name : "Tim",
height : 71,
sport : "soccer",
quote : "Timmy the Tiger!"
}
var anne = {
name : "Anne",
height : 66,
sport : "zumba",
quote : "Anne Gonna Dance All Over Ya!"
}
//function to add a "win" property and default value to each athlete object
function addWinners(atheletes){
for(var i = 0; i < atheletes.length; i++)
atheletes[i].win = (atheletes[i].name + " won " +
atheletes[i].sport);
console.log(atheletes[i].win);
}
fridays_contestants=[tim,anne]
addWinners(fridays_contestants)
/*
Current output:
=>"Cannot read property 'win' of undefined"
Desired output:
=>Tim won soccer
=>Anne won zumba
*/
Upvotes: 0
Views: 919
Reputation: 2254
var tim = {
name : "Tim",
height : 71,
sport : "soccer",
quote : "Timmy the Tiger!"
}
var anne = {
name : "Anne",
height : 66,
sport : "zumba",
quote : "Anne Gonna Dance All Over Ya!"
}
//function to add a "win" property and default value to each athlete object
function addWinners(atheletes){
for(var key in tim){
// var atheletes= (atheletes[i].name + " won " + atheletes[i].sport);
if (tim.hasOwnProperty(key)) {
alert(key + " -> " + tim[key]);
}
console.log(atheletes);
}
}
fridays_contestants=[tim,anne]
addWinners(fridays_contestants)
Upvotes: 1
Reputation: 42460
You did not start a code block after your for
loop using { ... }
. This way, only the statement directly after the loop will be executed inside the loop. Everything after that will be executed after the loop already finished and i
equals 2. Edit: i
should actually not exist anymore at the point where you call console.log()
, since it fell out of scope -- it has been declared inside the for
statement.
Try it like this instead:
for(var i = 0; i < atheletes.length; i++) {
atheletes[i].win = (atheletes[i].name + " won " +
atheletes[i].sport);
console.log(atheletes[i].win);
}
Upvotes: 3
Reputation: 1711
Should be
function addWinners(atheletes){
for(var i = 0; i < atheletes.length; i++)
{
atheletes[i].win = (atheletes[i].name + " won " +
atheletes[i].sport);
console.log(atheletes[i].win);
}
}
You missing {} for loop.
Upvotes: 1
Reputation: 57192
You don't have braces around your for loop, so you've effectively written
for(var i = 0; i < atheletes.length; i++) {
atheletes[i].win = (atheletes[i].name + " won " + atheletes[i].sport);
}
console.log(atheletes[i].win);
Use braces and put both statements inside.
Upvotes: 2