简体   繁体   中英

Trouble accessing values of array in javascript

I have an array in JavaScript that I receive from the back end and has the following structure:

scope.myArray = [{"0":[1,2,3,4],"1":[0,2,3,1,4]},{"0":[1,2,3,4],"1":[0,2,3,1,4]}]

I tried to retrieve some of the values by doing this:

for(var x=0;x<scope.myArray.length;x++){
    console.log("myArray is ....... " + JSON.stringify(scope.myArray[x].0))
}

and this

 for(var x=0;x<scope.myArray.length;x++){
    console.log("myArray is ....... " + JSON.stringify(scope.myArray[x]."0"))
}

but neither works.

Any help with this would be greatly appreciated. Thanks in advance.

You bracket notation , like this

 var myArray = [{"0":[1,2,3,4],"1":[0,2,3,1,4]},{"0":[1,2,3,4],"1":[0,2,3,1,4]}] for (var x = 0; x < myArray.length; x++) { console.log("myArray is ....... " + JSON.stringify(myArray[x][0])); } 

You should access the properties via bracket notation.

for (var x=0; x < scope.myArray.length; x++){
    console.log("myArray is ....... " + JSON.stringify(scope.myArray[x]['0']))
}

您创建了一个包含一个对象的数组,其键为“ 0”,“ 1”等。

Just try this:

scope.myArray = [
    {
        "0": [1, 2, 3, 4],
        "1": [0, 2, 3, 1, 4]
    }, 
    {
        "3": [1, 2, 3, 4],
        "4": [0, 2, 3, 1, 4]
    }
];
scope.myArray.forEach(function(item){
     console.log("myArray is ....... " + JSON.stringify(item[0]))
 });

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