在javascript中获取json对象的最后一个元素 [英] get last element of a json object in javascript
问题描述
我在javascript中有一个json对象,例如:
var json = {20121207:13,20121211:9,20121213:7 ,20121219:4};
,不知道最后一个键的名称。 (键按升序排列)
I got a json object in javascript like
var json = {"20121207":"13", "20121211":"9", "20121213":"7", "20121219":"4"};
without knowing the name of the last key. (The keys are in ascending order)
如何读取最后一个元素的值(和键)?
How can I read the value (and key) of the last element?
推荐答案
var highest = json[ Object.keys(json).sort().pop() ];
Object.keys
(ES5,可调节)返回对象键的数组。然后我们对它们进行排序并抓住最后一个。
Object.keys
(ES5, shimmable) returns an array of the object's keys. We then sort them and grab the last one.
您无法确保中的订单for..in
循环,所以我们不能完全依赖它。但正如你所说的那些键是按升序排列的,我们可以简单地对它们进行排序。
You can't ensure order in a for..in
loop, so we can't completely rely on that. But as you said the keys are in ascending order, we can simply sort them.
这篇关于在javascript中获取json对象的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!