我有一个数组包含
const data = ['a', 'b', 'c', 'd'];
如何找到最后一个元素,结果应该是'd'
使用函数slice
+解构赋值。
const data = ['a', 'b', 'c', 'd'],
[last] = data.slice(-1);
console.log(last);
您可以从末尾(负索引)切片并获取数组的项目。
const data = ['a', 'b', 'c', 'd'];
console.log(data.slice(-1)[0]);
过去,PrototypeJS 库向数组添加了方法,例如first
和last
. 因此,如果您想要替代data[data.length - 1]
,您可以在标准工具包中有一个实用方法:
Object.defineProperty(Array.prototype, "last", {
value() {
return this[this.length - 1];
},
enumerable: false, // (This is the default, you can leave it off if you like)
writable: true,
configurable: true
});
然后使用它:
console.log(data.last()); // 'd'
也有一个积极的提议将其添加到 JavaScript 中。
现场示例:
// In the toolkit
Object.defineProperty(Array.prototype, "last", {
value() {
return this[this.length - 1];
},
writable: true,
configurable: true
});
// Using it:
const data = ['a', 'b', 'c', 'd'];
console.log(data.last());
重要的是用于defineProperty
创建您添加的任何属性Array.prototype
(或天堂forfend,Object.prototype
)离开enumerable
标志(或设置它false
,这是默认值),以便您添加的内容是不可枚举的(不会出现在for-in
循环中)。(你通常不应该使用for-in
遍历数组——而是做这些事情之一 ——但是......人们会这样做。)如果你只是这样做了Array.prototype.last = function() { /*...*/ };
,那last
将是可枚举的。
请确保仅在您自己的应用程序/页面代码中执行此操作,而不是您编写和分发为库的代码。修改内置原型(除了 polyfill),即使使用defineProperty
,在其他人将使用的库中通常是一个坏主意。
根据 ES2022,您可以使用Array.at()方法,该方法采用整数值并返回该索引处的项目。允许正整数和负整数。负整数从数组中的最后一项开始倒数。
演示:
const data = ['a', 'b', 'c', 'd'];
console.log(data.at(-1));