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

Ecmascript 6 如何使用es6获取数组项中的最后一个元素,ecmascript-6,Ecmascript 6,我有一个数组项列表,如何使用es6来控制最后一个元素,提前谢谢 例: 名单:{ a:100, b:200 } const items =[ { list: { a: 1, b: 2 }, detail: { c: 20 }, }, { list: { a: 100, b: 200 }, detail: { c: 2 }, } ] 只需记录

我有一个数组项列表,如何使用es6来控制最后一个元素,提前谢谢

例: 名单:{ a:100, b:200 }

const items =[
  {
    list: {
      a: 1,
      b: 2
    },
    detail: {
      c: 20
    }, 
  },
   {
    list: {
      a: 100,
      b: 200
    },
    detail: {
      c: 2
    }, 
  }
]

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

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

如果列表有3项,则长度为3,但最后一项索引为2,因为数组从0开始,所以只需执行以下操作:

console.log(items[items.length - 1])
文件: 试试这个

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

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

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

不需要使用ES6来执行您询问的操作。您可以使用以下任一选项:

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

但是,如果您执意使用ES6检索该值,我们可以利用spread运算符(这是ES6功能)检索该值:

/**
 * 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
[last,…others]=items.reverse();console.log(last)
(不要这样做)这是否回答了您的问题?
/**
 * 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
/**
 * 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