如何获取 JavaScript 对象中的最后一项?

发布于 2024-10-05 19:22:54 字数 174 浏览 4 评论 0原文

如果我有一个像这样的对象:

{ 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' }

如果我事先不知道列表会上升到“c”,除了循环访问该对象之外,是否有办法获取对象中的最后一项(例如 '胡萝卜')?

If I have an object like:

{ 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' }

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')?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

狂之美人 2024-10-12 19:22:54

是的,有一种方法使用Object.keys(obj)此页面对此进行了解释:

var fruitObject = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
Object.keys(fruitObject); // this returns all properties in an array ["a", "b", "c"]

如果您想要获取最后一个对象的值,你可以这样做:

fruitObject[Object.keys(fruitObject)[Object.keys(fruitObject).length - 1]] // "carrot"

Yes, there is a way using Object.keys(obj). It is explained in this page:

var fruitObject = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
Object.keys(fruitObject); // this returns all properties in an array ["a", "b", "c"]

If you want to get the value of the last object, you could do this:

fruitObject[Object.keys(fruitObject)[Object.keys(fruitObject).length - 1]] // "carrot"
朦胧时间 2024-10-12 19:22:54

不会。 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.

枯叶蝶 2024-10-12 19:22:54
last = Object.keys(obj)[Object.keys(obj).length-1];

其中 obj 是你的对象

last = Object.keys(obj)[Object.keys(obj).length-1];

where obj is your object

花桑 2024-10-12 19:22:54

其他答案对我来说过于复杂。

let animals = {
  a: 'dog',
  b: 'cat',
  c: 'bird'
}

let lastKey = Object.keys(animals).pop()
let lastValue = animals[Object.keys(animals).pop()]

The other answers overcomplicate it for me.

let animals = {
  a: 'dog',
  b: 'cat',
  c: 'bird'
}

let lastKey = Object.keys(animals).pop()
let lastValue = animals[Object.keys(animals).pop()]
别理我 2024-10-12 19:22:54
var myObj = {a: 1, b: 2, c: 3}, lastProperty;
for (lastProperty in myObj);
lastProperty;
//"c";

来源:http://javascriptweblog.wordpress.com< /a>

var myObj = {a: 1, b: 2, c: 3}, lastProperty;
for (lastProperty in myObj);
lastProperty;
//"c";

source:http://javascriptweblog.wordpress.com

明天过后 2024-10-12 19:22:54

使用ES6解构赋值语法的解决方案:

var temp = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
var { [Object.keys(temp).pop()]: lastItem } = temp;
console.info(lastItem); //"carrot"

Solution using the destructuring assignment syntax of ES6:

var temp = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
var { [Object.keys(temp).pop()]: lastItem } = temp;
console.info(lastItem); //"carrot"

卸妝后依然美 2024-10-12 19:22:54

你可以试试这个。这将存储最后一个项目。这里需要将obj转换为数组。然后使用数组 pop() 函数从转换后的数组中返回最后一项。

var obj = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
var last = Object.keys(obj).pop();
console.log(last);
console.log(obj[last]);

You can try this. This will store last item. Here need to convert obj into array. Then use array pop() function that will return last item from converted array.

var obj = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
var last = Object.keys(obj).pop();
console.log(last);
console.log(obj[last]);

宛菡 2024-10-12 19:22:54

至于Javascript中对象属性的顺序,我将链接到这个答案:

“for (... in ...)”循环中的元素顺序

具体来说:

所有现代实现
ECMAScript 迭代对象
属性按照它们的顺序
被定义

所以这里的所有其他答案都是正确的,没有官方保证对象属性的顺序。然而在实践中是存在的(除非任何自然会搞砸官方指定行为的错误)。

此外,对象属性的实际枚举顺序可能会在未来的 EMCAScript 规范中进行编纂。

不过,目前我不会围绕此编写代码,主要是因为没有内置工具来帮助处理对象属性顺序。您可以编写自己的属性,但最终您总是会循环遍历对象中的每个属性以确定其位置。

因此,您的问题的答案是,除了循环访问对象之外没有其他办法。

As for the ordering of object properties in Javascript, I will just link to this answer:

Elements order in a "for (… in …)" loop

Specifically:

All modern implementations of
ECMAScript iterate through object
properties in the order in which they
were defined

So every other answer here is correct, there is no official guaranteed order to object properties. However in practice there is (barring any bugs which naturally can screw up even set-in-stone officially specified behavior).

Furthermore, the de-facto enumeration order of object properties is likely to be codified in future EMCAScript specs.

Still, at this time I would not write code around this, mostly because there are no built-in tools to help deal with object property order. You could write your own, but in the end you'd always be looping over each property in an object to determine its position.

As such the answer to your question is No, there is no way besides looping through an object.

季末如歌 2024-10-12 19:22:54

如果顺序很重要,请使用数组,而不是对象文字。

const list = ['apple', 'banana', 'carrot'];

或者类似的东西

const dict = {
 'a' : ['apple', 'awesome'],
 'b' : ['best friend']
};

,或者甚至..

const dict = [{letter:'a', list:['apple', 'awesome']},
              {letter:'b', list:['best friend']}];

dict 的键根本不保证是有序的。

Use an array, not an object literal, if order matters.

const list = ['apple', 'banana', 'carrot'];

Or something like

const dict = {
 'a' : ['apple', 'awesome'],
 'b' : ['best friend']
};

Or even..

const dict = [{letter:'a', list:['apple', 'awesome']},
              {letter:'b', list:['best friend']}];

The keys for dict are not guaranteed at all to be in order.

删除→记忆 2024-10-12 19:22:54
JSArray = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };  
document.write(Object.keys(JSArray)[Object.keys(JSArray).length-1]);// writes 'c'   
document.write(JSArray[Object.keys(JSArray)[Object.keys(JSArray).length-1]]); // writes 'carrot'
JSArray = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };  
document.write(Object.keys(JSArray)[Object.keys(JSArray).length-1]);// writes 'c'   
document.write(JSArray[Object.keys(JSArray)[Object.keys(JSArray).length-1]]); // writes 'carrot'
夏日浅笑〃 2024-10-12 19:22:54

您还可以使用 Object.values() 方法:

Object.values(fruitObject)[Object.values(fruitObject).length - 1]; // "carrot"

Edit

要提高性能,您可以创建一个变量:

constfruitValues = Object.values(fruitObject);

给你:

fruitValues[fruitValues.length - 1];

You could also use the Object.values() method:

Object.values(fruitObject)[Object.values(fruitObject).length - 1]; // "carrot"

Edit

To improve performance, you could create a variable:

const fruitValues = Object.values(fruitObject);

To give you:

fruitValues[fruitValues.length - 1];

情何以堪。 2024-10-12 19:22:54
const fruitObject = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
const lastValue = Object.values(fruitObject).slice(-1)[0];

看来路途很短。

https://developer.mozilla.org/de/文档/Web/JavaScript/Reference/Global_Objects/Object/values
https://developer.mozilla.org/de/文档/Web/JavaScript/Reference/Global_Objects/Array/slice

const fruitObject = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
const lastValue = Object.values(fruitObject).slice(-1)[0];

It seems to be a short way.

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/values
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

你的心境我的脸 2024-10-12 19:22:54

JavaScript 中的地图对象
。现在已经有3年左右的历史了。此地图数据结构保留项目插入的顺序。这样,检索最后一个项目实际上会导致最新的项目插入到地图中

Map object in JavaScript
. This is already about 3 years old now. This map data structure retains the order in which items are inserted. With this retrieving last item will actually result in latest item inserted in the Map

风流物 2024-10-12 19:22:54

obj 成为您的对象。执行:

(_ => _[Object.keys(_).pop()])( obj )

Let obj be your object. Exec:

(_ => _[Object.keys(_).pop()])( obj )
泪是无色的血 2024-10-12 19:22:54

如果您的意思是按字母顺序获取最后一个密钥,您可以(保证):

var obj = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
var keys = Object.keys(obj);
keys.sort();
var lastkey = keys.pop() // c
var lastvalue = obj[lastkey] // 'carrot'

if you mean get the last key alphabetically, you can (garanteed) :

var obj = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
var keys = Object.keys(obj);
keys.sort();
var lastkey = keys.pop() // c
var lastvalue = obj[lastkey] // 'carrot'
躲猫猫 2024-10-12 19:22:54
 const obj = { a: 'apple', b: 'banana', c: 'carrot' };
    
    // Get the last value using slice
    const values = Object.values(obj);
    const lastValue = values.slice(-1)[0];
    
    console.log(`Last value: ${lastValue}`);
    // Last value: carrot
 const obj = { a: 'apple', b: 'banana', c: 'carrot' };
    
    // Get the last value using slice
    const values = Object.values(obj);
    const lastValue = values.slice(-1)[0];
    
    console.log(`Last value: ${lastValue}`);
    // Last value: carrot
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文