如何使用JavaScript获取数组中的最后一个元素

6

我有一个数组列表,像这样:

const items = [
  { a: 1 },
  { b: 2 },
  { c: 3 },
]

如何返回/记录最后一个元素:{ c:3 }

以下是我目前尝试过的方法:

let newarray = items.map((item) => {
    console.log(item);
})

console.log(newarray);

如果你真的想使用es6 [last, ...others] = items.reverse(); console.log(last)(不要这样做) - Andrew Allen
1
这个回答解决了你的问题吗?[使用es6解构获取数组的最后一个元素] (https://dev59.com/JlwY5IYBdhLWcg3wD0PG) - Andrew Allen
7个回答

28

好的回答。但是在术语上有误导性,因为它声称Array.at()是ECMAScript 2021标准的一部分 - 然而在撰写本评论时(04.02.22),它仍然是第4阶段的提案。https://tc39.es/proposal-relative-indexing-method/#sec-array-prototype-additions - avalanche1
感谢@avalanche1 - 已更新答案以澄清。似乎第四阶段是一个完成的提案,将在下一个ECMAScript版本发布时发布。 - KyleMit

8

只需记录长度减1,与ES6无关:

console.log(items[items.length - 1])

3

2

更新 - 2021年10月(Chrome 97+)

提案 Array.prototype.findLastArray.prototype.findLastIndex 现在已经进入 Stage 3!

您可以像这样使用它:

const items = [
  { a: 1 },
  { b: 2 },
  { c: 3 },
];

const last_element = items.findLast((item) => true);
console.log(last_element);


这看起来很有前途。但是仍然不支持Firefox。你有想法如何使用现有的ES6+语法模仿它吗?(带有条件,如item.is_active == 'yes' - Nipuna
1
嗨。只需执行此操作items.findLast((item) => item.is_active === 'yes');即可。 - NeNaD
是的,我明白了。但问题是,这在Firefox中不受支持,而且该方法本身相对较新,因此一些旧浏览器不支持它。我正在寻找适用于Firefox和旧版浏览器的解决方案。ES6+就可以了。 - Nipuna
这个可行,const activeKeys = items.map(item => item.is_active); const lastActiveIndex = activeKeys.lastIndexOf('yes') - Nipuna

2

我想让你尝试一些不同的东西:

console.log(items.slice(-1));

3
items.slice(-1)[0] - alkhatim
如果之前的评论不够清晰,slice() 返回一个数组。items.slice(-1) 返回一个包含 items 最后一个元素的数组。items.slice(-1)[0] 则是元素本身,也就是 items 中的最后一项。 - Paul

2

您无需使用ES6即可执行您所询问的操作。您可以使用以下任一选项:

/**
 * The last value in the array, `3`, is at the '2' index in the array.
 * To retrieve this value, get the length of the array, '3', and 
 * subtract 1. 
 */
const items = [1, 2, 3];
const lastItemInArray = items[items.length - 1] // => 3

或者:

/**
 * Make a copy of the array by calling `slice` (to ensure we don't mutate
 * the original array) and call `pop` on the new array to return the last  
 * value from the new array.
 */
const items = [1, 2, 3];
const lastItemInArray = items.slice().pop(); // => 3

然而,如果你坚决要使用ES6来检索这个值,我们可以利用扩展运算符(这是一个ES6特性)来检索该值:

/**
 * Create new array with all values in `items` array. Call `pop` on this 
 * new array to return the last value from the new array.
 *
 * NOTE: if you're using ES6 it might be a good idea to run the code
 * through Babel or some other JavaScript transpiler if you need to
 * support older browsers (IE does not support the spread operator).
 */
const items = [1, 2, 3];
const lastItemInArray = [...items].pop(); // => 3

1
尝试这个。
console.log(items[items.length - 1]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接