I need to iterate from 0 to 30, but I want to do this with help of forEach
:
new Array(30).forEach(console.log.bind(console);
Of course this does not work, therefor I do:
new Array(30).join(',').split(',').forEach(console.log.bind(console));
Is there other ways to fill empty arrays?
I need to iterate from 0 to 30, but I want to do this with help of forEach
:
new Array(30).forEach(console.log.bind(console);
Of course this does not work, therefor I do:
new Array(30).join(',').split(',').forEach(console.log.bind(console));
Is there other ways to fill empty arrays?
Share Improve this question edited Apr 29, 2014 at 9:07 xdazz 161k38 gold badges253 silver badges278 bronze badges asked Apr 29, 2014 at 9:03 3y33y3 8021 gold badge6 silver badges18 bronze badges 1- 1 Use for loop instead. – Mike Grabowski Commented Apr 29, 2014 at 9:05
5 Answers
Reset to default 4Actually, there's a simple way to create a [0..N)
(i.e., not including N
) range:
var range0toN = Object.keys(Array.apply(0,Array(N)));
Apparently Object.keys
part can be dropped if you only want to get a proper array of N elements.
Still, like others said, in this particular case it's probably better to use for
loop instead.
if you want all of item have same value, do this
var arrLength = 4
var arrVal = 0
var newArr = [...new Array(arrLength)].map(x => arrVal);
// result will be [0, 0, 0, 0]
You could try using a for loop. new Array is not a best practise
var index, // we use that in the for loop
counter, // number of elements in array
myArray; // the array you want to fill
counter = 30;
myArray = [];
for (index = 0; index < counter; index += 1) {
myArray[index] = [];
/*
// alternative:
myArray.push([]);
// one-liner
for (index = 0; index < counter; index += 1) myArray.push([]);
*/
}
If you simply want to iterate, then use for
loop like this
for (var i = 0; i < 30; i += 1) {
...
...
}
Actually, if you are looking for a way to create a range of numbers, then you can do
console.log(Array.apply(null, {length: 30}).map(Number.call, Number));
It will create numbers from 0 to 29. Source : Creating range in JavaScript - strange syntax
If you insist foreach
var data = [1, 2, 3];
data.forEach(function(x) {
console.log(x);
});