不需要使用 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