获取javascript对象中的最后一项 [英] getting the last item in a javascript object
问题描述
如果我有一个像这样的对象:
If I have an object like:
{ 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' }
如果我事先不知道列表是直到'c',除了循环对象,有没有办法获取对象中的最后一项(例如'胡萝卜'
)?
If I don't know in advance that the list goes up to 'c', other than looping through the object, is there a way to get the last item in the object (e.g. 'carrot'
)?
推荐答案
不。在JSON和大多数其他键值数据结构中无法保证顺序,因此最后一项有时可能是 carrot
,有时则 banana
等等。如果您需要依赖订购,那么最好的选择是使用数组。键值数据结构的强大之处在于通过键
访问值,而不是能够获得 nth
对象的项目。
No. Order is not guaranteed in JSON and most other key-value data structures, so therefore the last item could sometimes be carrot
and at other times be banana
and so on. If you need to rely on ordering, your best bet is to go with arrays. The power of key-value data structures lies in accessing values by their keys
, not in being able to get the nth
item of the object.
这篇关于获取javascript对象中的最后一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!