简体   繁体   English

jQuery / javascript命名索引数组与数组关联

[英]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']? 如何在signOptionSet ['basic']中访问“ Sign Height”之类的内容?

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. 没有什么技术上的错误吧,只要你明白,有些东西(比如JSON.stringify )将不会看到那些非索引属性。

How would I access something like 'Sign Height' in signOptionSet['basic']? 如何在signOptionSet ['basic']中访问“ Sign Height”之类的内容?

It's the second entry, so index 1, of the array you've assigned to signOptionSet['basic'] , so: 这是您分配给signOptionSet['basic']的数组的第二个条目,即索引1,因此:

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): 单引号和双引号在JavaScript中均有效(单引号不在JSON中,但这不是JSON,它是JavaScript):

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

You access the value 'Sign Height' like 您可以像访问“ Sign Height”这样的值

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

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM