1

Object:

obj = {
    "expired":93,
    "old3":93,
    "old2":87,
    "old1":100,
    "fresh":150
}

How would I find the index of "old1" (so, 3) in an object?

How would I go about referencing "old1" by its index if I wanted to set its value?

4

2 回答 2

2

您不应该这样做,不能保证对象属性的顺序。

如果要使用数字索引,请改用数组。

如果您使用所有字符串键(不是数字格式),那么大多数浏览器都会尊重对象表达式的顺序,但这并不能保证。

如果您包含数字或数字格式字符串作为键,那么顺序将不是对象表达式的顺序。看:

var obj = {
    "expired":93,
    "old3":93,
    "old2":87,
    "old1":100,
    "1": 111,
    "fresh":150
};

for (var key in obj) {
    console.log(key + ' : ' + obj[key]);
}

输出:

1 : 111
expired : 93
old3 : 93
old2 : 87
old1 : 100
fresh : 150 
于 2012-09-20T02:26:27.250 回答
0

对于仍在寻找它的人......我得到了这个解决方案:

<div id="id"></div>
<div id="name"></div>
<div id="age"></div>

var data = {'rows':[
{'id':'1','name':'Andrey','age':'18'},
{'id':'2','name':'Cristine','age':'21'},
{'id':'3','name':'Loren','age':'25'}
]};

$('#id').html(data.rows[0][Object.keys(data.rows[0])[0]]);
$('#name').html(data.rows[0][Object.keys(data.rows[0])[1]]);
$('#age').html(data.rows[0][Object.keys(data.rows[0])[2]]);

jsfiddle

于 2016-07-03T02:47:06.527 回答