简体   繁体   中英

What kind of array is this in JavaScript?

I have an array that looks like this:

var locationsArray = [['title1','description1','12'],['title2','description2','7'],['title3','description3','57']];

I can't figure out what type of array this is. More importantly, I'm gonna have to create one based on the info there. So, if the number on the end is greater than 10 then create a brand new array in the same exact style, but only with the title and description.

var newArray = [];
// just a guess
if(locationsArray[0,2]>10){
   //add to my newArray like this : ['title1','description1'],['title3','description3']
   ? 
}

How can I do it?

Try like below,

var newArray = [];

for (var i = 0; i < locationsArray.length; i++) {
   if (parseInt(locationsArray[i][2], 10) > 10) {
      newArray.push([locationsArray[i][0], locationsArray[i][1]]);
   }
}

DEMO: http://jsfiddle.net/cT6NV/

It's an array of arrays, also known as a 2-dimensional array. Each index contains its own array that has its own set of indexes.

For instance, if I retrieve locationsArray[0] I get ['title1','description1','12'] . If I needed to get the title from the first array, I can access it by locationsArray[0][0] to get 'title1' .

Completing your example:

var newArray = [];
// just a guess
if(locationsArray[0][2]>10){
   newArray.push( [ locationsArray[0][0], locationsArray[0][1] ] );
}

throw that in a loop and you're good to go.

It's an array of arrays of strings.

Each time there is this : [], it defines an array, and the content can be anything (such as another array, in your case).

So, if we take the following example :

var myArray = ["string", "string2", ["string3-1", "string3-2"]];

The values would be as such :

myArray[0] == "string"
myArray[1] == "string2"
myArray[2][0] == "string3-1"
myArray[2][1] == "string3-2"

There can be as many levels of depth as your RAM can handle.

locationsArray is an array of arrays. The first [] operator indexes into the main array (eg locationsArray[0] = ['title1','description1','12']) while a second [] operation indexes into the array that the first index pointed to (eg locationsArray[0][1] = 'description1').

Your newArray looks like it needs to be the same thing.

It's an array of array.

var newArray = [];
var locationsArray = [
    ['title1','description1','12'],
    ['title2','description2','7'],
    ['title3','description3','57']
];

for(i = 0; i < locationsArray.length; i++) {
    if (locationsArray[i][2] > 10) {
        newArray .push([locationsArray[i][0], locationsArray[i][1]]);
    }
}

console.log(newArray );

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