I am still newbie in javascript
I am looking for a simple loop in javascript with iteration over integers where I am not interested in the item.
in python it looks like this: for i in range(10)
in ruby: (1..10).each
the simplest example in javascript I found is this:
_.each(Array.apply(null, new Array(10)).map(Number.prototype.valueOf,0)
Do you familiar with simpler example?
-
1Google "javascript loops".user1636522– user16365222013年12月01日 10:15:23 +00:00Commented Dec 1, 2013 at 10:15
-
"where I am not interested in the item" - What are you interested in? Please describe more clearly what output you expect.nnnnnn– nnnnnn2013年12月01日 10:17:51 +00:00Commented Dec 1, 2013 at 10:17
-
1for someone who can come up with loops in several other languages am amazed couldn't find answer in 3 minutes doing web searchcharlietfl– charlietfl2013年12月01日 10:25:11 +00:00Commented Dec 1, 2013 at 10:25
-
kind of 'i don't even want to bother searching' post.GameAlchemist– GameAlchemist2013年12月01日 10:43:37 +00:00Commented Dec 1, 2013 at 10:43
7 Answers 7
You could use a simple for loop:
for (let i = 0; i < 10; i++) {
// i is your integer
}
Comments
Recursive function :
function loop(n, fn) {
n && (fn(), loop(--n, fn));
}
Usage :
loop(3, function () {
alert('One more time!')
});
1 Comment
While loop:
var i = 10; while (i--) {
// do something 10 times
}
Comments
If you are using Underscore and you prefer a functional programming style, which your example suggests, try this:
_.times(5, function(e) { console.log(e) })
1 Comment
I was looking for this, because a needed to split and get each integer from long integers. I solved doing:
let getArrayToLoop = theNumber.toString().split('');
// then you can loop with for, for ... in, map
for(let i = 0; i < getArrayToLoop.length; i++) {
console.log(getArrayToLoop[i]) // this is a string, you could
//Number(getArrayToLoop[i]) *if needed
}
Comments
Python's range(n) call when used with one argument, corresponds to JavaScript's Array(n).keys():
for (const i of Array(4).keys()) {
console.log(i);
}
As of ECMAScript 2025 you can also chain a forEach (iterator helper) call to it:
Array(4).keys().forEach(i => console.log(i));
Comments
<!DOCTYPE html>
<html>
<body>
<p>Click the button to loop through a block of code five times.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="",i;
for (i=0;i<5;i++)
{
x=x + "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>