0

Push multi values in javascript array and get the first element?

Below, I am trying to push 3 different values in a array:

var a = [];
a.push([1, 'b', 'c']);
DBG.write("test:" + a[0]); //output: 1, b, c

how to print the the first element on this array?

output should be: 1

  • 2
    `a[0][0]` as `a[0]` is an array! – Rayon May 03 '16 at 13:38
  • To build on what @Rayon said, `Array.push` expects direct values, and not an array. `a.push([1, 'b', 'c'])` is pushing an array to the first element of `a`. – ArcSine May 03 '16 at 13:42
  • @ArcSine, _"Array.push expects direct values, and not an array"_ .. No buddy! It is ok with anything.. `undefined` as well.. – Rayon May 03 '16 at 13:43
  • It accepts arrays, but it will add it as an array. `a.push(1,2,3)` is different than `a.push([1,2,3])` – ArcSine May 03 '16 at 13:54

3 Answers3

3

You are pushing in an array. Try

a.push(1, 'b', 'c');

to push in 3 separate values.

And to print it:

DBG.write("test:" + a[0]);

(or, if you want to push in the array like you did in your question, use

DBG.write("test:" + a[0][0]);

to get the first element of that array).

Feathercrown
  • 2,547
  • 1
  • 16
  • 30
1

If you want to add items from array then use concat. In your case when you push and array into an array then it becomes a multi-dimensional array (assuming that was not the intention), it became [[1,'b','c']].

Replace

a.push([1, 'b', 'c']);

with

a = a.concat([1, 'b', 'c']);

You can print the first element by doing same thing DBG.write("test:" + a[0]);

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1
a[0] // output [1, 'b', 'c']  

By doing

DBG.write("test:" + a[0][0]); // output 1
ozil
  • 6,930
  • 9
  • 33
  • 56
  • This is giving the right result, but I would recommend to use the other solution, since this is the behavior I think would make more sense. – Kiksen May 03 '16 at 13:44