Get Number From One To X In A Loop?
How do I get all the digits from 0 - x if x is a variable like so: var x = 5 Then loop then so it logs them all individually by console.log()? I was thinking I could use .each(),
Solution 1:
Like this? http://jsfiddle.net/howderek/KKgPT/
x = 5;
for (i = 0;i <= x;i++) {
console.log(i);
document.getElementById("result").innerHTML += i + ' ';
}
Solution 2:
var x = 5;
for (var i = 0; i <= x; i++)
console.log(i);
jQuery's $.each()
method is for iterating over an object or array, so it doesn't make sense for this problem though you can do something silly like this:
$.each(new Array(x+1), function(i) {
console.log(i);
});
I.e., create a new array with x+1
elements, and then iterate over it specifically to use the index values. I do not recommend this, but since you asked about jQuery...
Solution 3:
This is really pretty basic:
for (var i = 0; i < x; ++i) console.log(i);
(Use <=
if you want to include the value of x
in the output.)
Post a Comment for "Get Number From One To X In A Loop?"