简体   繁体   中英

Javascript Storing in Array

I don't know how to categorise the type of array that i need. The type of array i require is one which can store 3 different values in a collection.

For Example

var Array = [["John", "Smith", "39"],["Michael", "Angel", "76"]]

Each time i push new data to array in the same format of [Forename, Surname, Age]. How do i declare the array and add data to the array in this format?

Then once in the array retrieve it such as print each collection to console log for example in the following format.

console.log("John" + "Smith" + "39")
console.log("Michael" + "Angel" + "76")

Array.push(["a", "b", "c" ])

This would work, push allows you to append to an array and you can have a list within the push to create 2d arrays

myObj = Array[0]; //index of required data
console.log(myObj[0] + myObj[1] + myObj[2])

This would then give the data output in the format you want, but would just be a very long string...

First of all, don't call your variable Array because Array is already a type defined in the ECMAScript standard. Redefining Array may have undefined behavior (read: Very Bad Things). In my example code below, I've renamed it to myArray .

In your example, your array is an array of arrays, ie every element is another array. In order to push more data into your top-level array, simply call .push() .

myArray.push(["Joe", "Somebody", "43"]);

If you're looking to display a record on the console, you can use a compound index:

var myArray = [["John", "Smith", "39"],["Michael", "Angel", "76"]];
// prints MichaelAngel76
console.log(myArray[1][0] + myArray[1][1] + myArray[1][2])
// prints JohnSmith39
console.log(myArray[0][0] + myArray[0][1] + myArray[0][2])

Or if you want to display every record:

// prints:
// JohnSmith39
// MichaelAngel76
myArray.forEach(function (elem) {
    console.log(elem[0] + elem[1] + elem[2]);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM