Reputation: 29
I have code like this:
$data = array();
for(int $i = 0; $i < 10; $i ++)
$data[$i][] = 5;
I don't know what's name of $data[$i][] = 5;
in php and how to write this code in javascript?
or other hands, how can I write code above in javascript?
Thanks
P/s: I want to write that code on nodeJs
Upvotes: 0
Views: 85
Reputation: 15846
Array.push() is a function used to insert a value into an array. But you can also use the C like way data[i] = 'value'
.
data = [];
for (var i = 0; i < 10; i++)
data.push([5]);
document.write(JSON.stringify(data))
As an alternative use
data = [];
for(var i = 0; i < 10; i ++)
data[i] = [5];
document.write(JSON.stringify(data));
Upvotes: 1
Reputation: 96
JavaScript code:
var data = [];
for (i = 0; i < 10; i++) {
data[i] = [];
data[i][data[i].length] = 5;
}
Upvotes: 0
Reputation: 1326
You can try Array#push
to add a element for array
var data = [];
for(var i = 0; i < 10; i ++)
if(!data[i]) data[i] = [];
data[i].push(5);
Upvotes: 1
Reputation: 186
in this case, can understand $data[$i][] = 5;
as below
$data[$i] = array();
array_push($data[$i],5);
// ex: [ 0 => [0 => 5]]
in Javascipt:
var data = [];
for (var i = 0; i < 10; i ++){
data[i] = [];
data[i].push(5);
}
Upvotes: 1
Reputation: 726
Use array.push()
to add an item to the end of the array.
var sample = new Array();
sample.push(new Object());
To do this n times use a for loop.
var n = 100;
var sample = new Array();
for (var i = 0; i < n; i++)
sample.push(new Object());
Note that you can also substitute new Array()
with [] and new Object()
with {} so it becomes:
var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({});
Upvotes: 0