-->

Creating a 2d associative array javascript (same a

2020-04-19 06:35发布

问题:

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.

回答1:

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'


回答2:

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



回答3:

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.



回答4:

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']);