简体   繁体   中英

Creating a 2d associative array javascript (same as a php assoc array)

I am trying to create an array in javascript which will allow me to access data like this:

var name = infArray[0]['name'];

however I cant seem to get anything to work in this way. When i passed out a assoc array from php to javascript using json_encode it structured the data in this way. The reason why i have done this is so i can pass back the data in the same format to php to execute an update sql request.

JavaScript doesn't have associative arrays. It has (numeric) arrays and objects.

What you want is a mix of both. Something like this:

var infArray = [{
    name: 'Test',
    hash: 'abc'
}, {
    name: 'something',
    hash: 'xyz'
}];

Then you can access it like you show:

var name = infArray[0]['name']; // 'test'

or using dot notation:

var name = infArray[0].name; // 'test'

只需var infArray = [{name: 'John'}, {name: 'Greg'}] ;-)

JavaScript doesn't have assoc arrays. Anything to any object declared as obj['somthing'] is equal to obj.something - and it is a property. Moreover in arrays it can be a bit misleading, so any added property won't changed array set try obj.length .

JavaScript do not have 2D associative array as such. But 2d associative array can be realized through below code:

var myArr = { K1: {
    K11: 'K11 val',
    K12: 'K12 Val'
    },
    K2: {
    K21: 'K21 Val',
    K22: 'K22 Val'
    }
};
alert(myArr['K1']['K11']);
alert(myArr['K1']['K12']);
alert(myArr['K2']['K21']);
alert(myArr['K2']['K22']);  

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