Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialGesang Lamu
2,742 PointsJs looping: problem with length, help!
So I am writing this simple method to loop through this array, but my console gives me an error say
"Uncaught TypeError: Cannot read property 'length' of undefined"
var array = ["apple","pear","juice"];
var msgs = function(array){ for(i=0; i < array.length; i++); console.log(array[i]); }
msgs();
I am pretty sure there is nothing wrong with the function, i googled it seem to be some problem with the server but I don't exactly get it. So seeking help here. Many thanks!
- Gesang
2 Answers
Sean T. Unwin
28,690 Pointsmsgs()
is defined as taking an argument but none are passed when you call it in the last line.
Also, you have forgotten the curly brackets for the for
loop.
The code should look similar to this:
var array = ["apple","pear","juice"];
var msgs = function(array){
for(var i=0; i < array.length; i++) {
console.log(array[i]);
}
}
msgs(array);
You were almost there; just needed a couple of tweaks. :)
Michael Alaev
5,415 PointsYou should add "Var" before your "i" variable that you are looping with.
Mike.
Gesang Lamu
2,742 Pointsoh you are right, like this
var msgs = function(array){ for(var i=0; i < array.length; i++){ console.log(array[i]); } }
adriendepraute
7,082 Pointsadriendepraute
7,082 PointsI'm wondering why is there an "undefined" at the end of the loop when running the code in the console ?
Stone Preston
42,016 PointsStone Preston
42,016 Pointsdoesnt i need to be declared as a var as well?
Gesang Lamu
2,742 PointsGesang Lamu
2,742 Pointsso here is my site http://myhundredwebsites.herokuapp.com/fortunecookies I am trying to make this happen with less code, image is problem is something with Rails I think but ignore it for now, when you click it still works.
var array = ["you are lucky","you are pretty lucky","you are very lucky"];
var msgs = function(array){ for(i=0; i < array.length; i++){ console.log(array[i]); } } msgs(array);
$(document).ready(function(){ $(".pinkfc,.fancyfc,.greenfc").click(function(){ $(this).fadeOut(2000); $(this).text(msgs(array));/ this is where the problem is I am taking a a wild guess but doesnt work $(this).css({'color':'#0000ff', 'font-size':'300%'});
}); });
.pinkfc,.fancyfc,.greenfc are the images wrapped in a class
Sean T. Unwin
28,690 PointsSean T. Unwin
28,690 PointsYou`re right, Stone Preston. I edited my comment.