使用 JavaScript 获取对象中的最后一项
要获取对象中的最后一项,请使用 Object.keys()
方法获取对象键的数组并在结果上调用 pop()
方法,例如 Object.keys(obj).pop()
。 pop()
方法将返回对象中的最后一个键。
const obj = {one: 1, two: 2, three: 3};
const lastKey = Object.keys(obj).pop();
console.log(lastKey); // 👉️ three
const lastValue = Object.values(obj).pop();
console.log(lastValue); // 👉️ 3
我们使用 Object.keys()
方法来获取对象键的数组。
const obj = {one: 1, two: 2, three: 3};
// 👇️ ['one', 'two', 'three']
console.log(Object.keys(obj));
最后一步是使用 Array.pop()
方法,该方法从数组中删除最后一个元素并将其返回。
// 👇️ "three"
console.log(Object.keys(obj).pop());
pop()
方法更改调用它的数组,但这在我们的场景中无关紧要,因为我们将键数组用作一次性数组。
我们可以通过访问特定键处的对象来获取与键对应的值。
const obj = {one: 1, two: 2, three: 3};
const lastKey = Object.keys(obj).pop();
console.log(lastKey); // 👉️ three
const v = obj[lastKey];
console.log(v); // 👉️ 3
我们使用方括号表示法来访问与属性关联的值。
我们可以直接访问对象中的最后一个值,方法是使用 Object.values()
方法获取对象值的数组并对结果调用 pop()
方法,例如 Object.values(obj).pop()
。
const obj = {one: 1, two: 2, three: 3};
const lastValue = Object.values(obj).pop();
console.log(lastValue); // 3
Object.values
方法返回一个包含对象值的数组,我们可以在该数组上使用 pop()
方法获取最后一个值。
另一种方法是使用 Object.entries
方法,它返回一个包含键值对子数组的数组。
const obj = {one: 1, two: 2, three: 3};
const [key, value] = Object.entries(obj).pop();
console.log(key); // 👉️ three
console.log(value); // 👉️ 3
Object.entries()
方法返回一个二维数组。
// 👇️ [['one', 1], ['two', 2], ['three', 3]]
console.log(Object.entries(obj));
我们使用 pop()
方法获取最后一个包含键值对的子数组。
最后一步是使用解构赋值将第一个和第二个数组元素分配给键和值变量。
const [key, value] = ['three', 3];
console.log(key); // 👉️ three
console.log(value); // 👉️ 3
考虑解构赋值的一种简单方法是——我们将数组元素赋给变量。
请注意
,分配的顺序将被保留。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。