简体   繁体   English

使用数字键访问非数字密钥对象是有效的JavaScript吗?

[英]is it valid javascript to access non-numeric key object with a numeric key?

I have an object 我有一个对象

data = {
    'choiceA' : 'Long-Wear',
    'choiceB' : 'Anti-Age Lifting/Firming',
    'choiceC' : 'Replenishing/ Moisturizing',
    'choiceD' : 'Natural/ True-to-Skin',
    'choiceE' : 'Smoothing/ Illuminating'
}    

and I need to retrieve the fourth value given an integer 我需要检索给定整数的第四个值

 position = 3;

normally I would write 通常我会写

 key = $.inArray( position, ['choiceA', 'choiceB', 'choiceC', 'choiceD', 'choiceE']);
 answer = data[key];

but is it valid javascript to access the object directly with the numeric key like this? 但是用这样的数字键直接访问对象是有效的javascript吗?

 answer = data[position];  // where position is an integer

EDIT: 编辑:
some bad code I wrote as I'm using $.inArray backwards! 我写的一些不好的代码,因为我正在向后使用$ .inArray!
I meant to write 我打算写

 arr = ['choiceA', 'choiceB', 'choiceC', 'choiceD', 'choiceE'];
 key = arr[position];
 answer = data[key];

No, it is not valid until you have numeric object "keys", ie 不,在你有数字对象“键”之前它是无效的,即

data = {
    '1' : 'Long-Wear',
    '2' : 'Anti-Age Lifting/Firming',
    '3' : 'Replenishing/ Moisturizing',
    '4' : 'Natural/ True-to-Skin',
    '5' : 'Smoothing/ Illuminating'
};

Also, it is important to note, that properties in JavaScript objects are not sorted . 此外,需要注意的是,JavaScript对象中的属性未进行排序 So your solution is the best way to go as I see. 所以你的解决方案是我看到的最佳方式。

if you would have tried it, you would have seen that it is not valid. 如果你想尝试一下,你会发现它无效。 even more it is not working! 甚至更多它不工作!

data[position]

would return undefined in your example... 将在您的示例中返回undefined ...

Two things: 两件事情:

  1. Javascript keys are always strings. Javascript键始终是字符串。 If you pass something else (say, a number) it is converted to a string. 如果您传递其他内容(例如,数字),则会将其转换为字符串。 (For example, try indexing a array with array["3"] and it should work (例如,尝试使用array["3"]索引数组,它应该可以工作

  2. Javascript objects are not ordered! Javascript对象没有订购! You cannot get back the i-th key value pair portably. 您无法轻松取回第i个键值对。 Instead you should use an array to store things (or something like that): 相反,你应该使用一个数组来存储东西(或类似的东西):

     data = [ { name:'choiceA', value: 'Long-Wear'}, { name:'choiceB', value: 'Anti-Age Lifting/Firming'} ]; 

    One thing you could do if you can't change the data representation is iterate though your object using a for-in loop, plus a counting variable. 如果你不能改变数据表示,你可以做的一件事就是使用for-in循环和计数变量迭代你的对象。 However, this approach is not portable, since not all browsers iterate in the same order as the keys were defined. 但是,这种方法不可移植,因为并非所有浏览器都按照定义键的顺序进行迭代。

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

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