arrays - Why doesn't my javascript work? -
i'm trying create javascript count 1 1000 , push multiples of 3, 5 array called multiples print array out using console.log(). reason code isn't working. know why?
var n; var multiples = []; for(n = 1; n <= 1000; n += 1) { console.log("counting"); } if(n % 3 === 0) { n.push(multiples); } else { } if(n % 5 === 0) { n.push(multiples); } else { } if(n >= 1000) { console.log(multiples); } else { }
there few issues code. using {}
in block designates scope of code executing in each iteration. in order access each value n
need placing conditional statements inside of {}
, not outside of them.
there slight syntax error multiples array. in order push value array use arrayname followed dot operator , push function argument being value pushed. in terms of multiples , n, means multiples.push(n)
.
when using if()
block, else not required.
it best practice include variable declaration inside of loops, , use ++ opposed += 1.
overall, code need more this
var multiples = []; console.log("counting"); for(var n = 1; n <= 1000; n++) { if(n % 3 === 0) { multiples.push(n); } if(n % 5 === 0) { multiples.push(n); } } console.log(multiples);
Comments
Post a Comment