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
5 Answers 5
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);
6 Comments
$data[$i][] = 5 in php? or how is working with that code?$data[$i][] = 5 equivalent $data[$i][count($data[$i])] = 5 to add a new element to arraydata[i] = [] var data = []; for (var i = 0; i < 10; i ++){ data[i] = []; data[i].push(5); }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);
}
1 Comment
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));
Comments
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({});
Comments
JavaScript code:
var data = [];
for (i = 0; i < 10; i++) {
data[i] = [];
data[i][data[i].length] = 5;
}