Is it possible to have an array of arrays? [closed]

-1

Is it possible to insert an array into another array as an element? That is, make an array of arrays? I.e.:

array[

       [0] => valor => array( 
                             [0]=> valor 1, 
                             [1]=> valor 2,
                             [2]=> valor 3 
                            )

     ];
    
asked by anonymous 17.07.2017 / 14:53

1 answer

2

Editing

According to the author of the question, commenting on this answer:

  

You can do this in the form "{" 1 ": [{" name ":" John "," Age ":" 21 "}]" 2 ": [{" name ":" Jone " "22"}]}

Apparently you want to mount a JSON, where each property is a sequential number. What you need then is not an array, but an object.

When converting an array to JSON, you will have only its elements:

JSON.stringify(['fus', 'ro', 'dah']);
// resulta em "["fus", "ro", "dah"]"

For each key to be represented textually in JSON, you need the following construct. Try the console:

var objeto = {};
objeto["1"] = { name: "John", age: "21"};
objeto["2"] = { name: "Jone", age: "22"};
JSON.stringify(objeto);

Note that:

  • You have an object that has other objects as properties. This is not an array of arrays;
  • In this way keys are not necessarily sequential - you can use anything in place of numbers. Note also that there may be no guarantee of ordering properties if you run in different browser environments.

Original answer

Yes, it is possible. Try the following code in the browser console:

var foo = [];
foo[0] = [1, 2, 3];
foo[1] = [4, 5, 6];
foo;

Note that this is not best practice. If you are going to enter directly into specific indexes, the responsibility of maintaining continuous indexes and ensuring that there is no accidental overwriting is yours. This is simple in a sample code like the above code, but as your code grows it becomes more complicated and open to bugs.

The best way is to use the default array insert:

var foo = [];
foo.push([1, 2, 3]);
foo.push([4, 5, 6]);
foo;
    
17.07.2017 / 15:00