简体   繁体   中英

Jquery/javascript named index array with array association

I want to know if its possible (and correct) to construct a named index array that is associated with other arrays.

Eg,

 var signOptionSet = []; signOptionSet['basic'] = ['Sign Width', 'Sign Height', 'Sign Depth', 'Base Material', 'Finish']; signOptionSet['advanced'] = ['Area', 'Perimeter', 'Lighting']; 

How would I access something like 'Sign Height' in signOptionSet['basic']?

I want to know if its possible...

Yes, although the way you're using it, you wouldn't want an array, you'd just want an object ( {} ) (see below).

...(and correct)...

Some would argue that using an array and then adding non-index properties to it is not correct. There's nothing technically wrong with it, provided you understand that some things (such as JSON.stringify ) won't see those non-index properties.

How would I access something like 'Sign Height' in signOptionSet['basic']?

It's the second entry, so index 1, of the array you've assigned to signOptionSet['basic'] , so:

var x = signOptionSet['basic'][1];

or

var x = signOptionSet.basic[1];

Using an object, and using property name literals as there's no need for strings here, would look like this:

var signOptionSet = {
    basic: ['Sign Width', 'Sign Height', 'Sign Depth', 'Base Material', 'Finish'],
    advanced: ['Area', 'Perimeter', 'Lighting']
};

You can use strings, though, if you prefer:

var signOptionSet = {
    "basic": ['Sign Width', 'Sign Height', 'Sign Depth', 'Base Material', 'Finish'],
    "advanced": ['Area', 'Perimeter', 'Lighting']
};

Both single and double quotes are valid in JavaScript (single quotes wouldn't be in JSON, but this isn't JSON, it's JavaScript):

var signOptionSet = {
    'basic': ['Sign Width', 'Sign Height', 'Sign Depth', 'Base Material', 'Finish'],
    'advanced': ['Area', 'Perimeter', 'Lighting']
};

You access the value 'Sign Height' like

alert(signOptionSet['basic'][1]) // 'Sign Height'

Fiddle

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