简体   繁体   English

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

[英]How the get the last element in an array items using JavaScript

I have a list of array items like this:我有一个这样的数组项列表:

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

How can I return / log the last element: { c: 3 }如何返回/记录最后一个元素: { c: 3 }

Here's what I've tried so far:到目前为止,这是我尝试过的:

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

console.log(newarray);

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

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

If your list has 3 items, the length is 3 but the last item index is 2, since arrays start at 0, so simply do this:如果您的列表有 3 个项目,则长度为 3,但最后一个项目索引为 2,因为数组从 0 开始,因此只需执行以下操作:

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

Doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array文档: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

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

Proposal for Array.prototype.findLast and Array.prototype.findLastIndex is now on Stage 3! Array.prototype.findLastArray.prototype.findLastIndex提案现在处于第 3 阶段!

You can use it like this:你可以像这样使用它:

 const items = [ { a: 1 }, { b: 2 }, { c: 3 }, ]; const last_element = items.findLast((item) => true); console.log(last_element);

尝试这个

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

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

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

It's not required to use ES6 to perform the operation you're asking about.不需要使用 ES6 来执行您所询问的操作。 You could use either of the following:您可以使用以下任一方法:

/**
 * 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

or:或者:

/**
 * 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

However, if you are dead set on using ES6 to retrieve this value we can leverage the spread operator (which is an ES6 feature) to retrieve the value:但是,如果您对使用 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM