我有一个数组列表,像这样:
const items = [
{ a: 1 },
{ b: 2 },
{ c: 3 },
]
如何返回/记录最后一个元素:{ c:3 }
以下是我目前尝试过的方法:
let newarray = items.map((item) => {
console.log(item);
})
console.log(newarray);
我有一个数组列表,像这样:
const items = [
{ a: 1 },
{ b: 2 },
{ c: 3 },
]
如何返回/记录最后一个元素:{ c:3 }
以下是我目前尝试过的方法:
let newarray = items.map((item) => {
console.log(item);
})
console.log(newarray);
Array.at()
是ECMAScript 2021标准的一部分 - 然而在撰写本评论时(04.02.22),它仍然是第4阶段的提案。https://tc39.es/proposal-relative-indexing-method/#sec-array-prototype-additions - avalanche1只需记录长度减1,与ES6无关:
console.log(items[items.length - 1])
console.log(items[items.length - 1]);
文档: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array
提案 Array.prototype.findLast
和 Array.prototype.findLastIndex
现在已经进入 Stage 3!
您可以像这样使用它:
const items = [
{ a: 1 },
{ b: 2 },
{ c: 3 },
];
const last_element = items.findLast((item) => true);
console.log(last_element);
item.is_active == 'yes'
) - Nipunaitems.findLast((item) => item.is_active === 'yes');
即可。 - NeNaDconst activeKeys = items.map(item => item.is_active); const lastActiveIndex = activeKeys.lastIndexOf('yes')
- Nipuna我想让你尝试一些不同的东西:
console.log(items.slice(-1));
slice()
返回一个数组。items.slice(-1)
返回一个包含 items
最后一个元素的数组。items.slice(-1)[0]
则是元素本身,也就是 items
中的最后一项。 - Paul您无需使用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
console.log(items[items.length - 1]);
[last, ...others] = items.reverse(); console.log(last)
(不要这样做) - Andrew Allen