0

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

asked Feb 19, 2016 at 6:07
0

5 Answers 5

1

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);
answered Feb 19, 2016 at 6:09
Sign up to request clarification or add additional context in comments.

6 Comments

This seems error: data[i][].push(5); ^ SyntaxError: Unexpected token ]
seems, working, Thanks but what's name of this code $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 array
Cannot read property 'push' of undefined. seem not working... I'm coding in node js
as i comment, you need set data[i] = [] var data = []; for (var i = 0; i < 10; i ++){ data[i] = []; data[i].push(5); }
|
1

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);
}

answered Feb 19, 2016 at 6:30

1 Comment

awesome!!. What I need. Thanks you!
1

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));

answered Feb 19, 2016 at 6:12

Comments

0

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({});
answered Feb 19, 2016 at 6:14

Comments

0

JavaScript code:

var data = [];
for (i = 0; i < 10; i++) {
 data[i] = [];
 data[i][data[i].length] = 5;
}
answered Feb 19, 2016 at 7:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.