Array.prototype.last = function() {
if (this.length === 0) {
return -1;
} else {
return this[this.length - 1];
}
};
// 示例使用:
const myArray = [1, 2, 3, 4, 5];
console.log(myArray.last()); // 5
const emptyArray = [];
console.log(emptyArray.last()); // -1
通过 Array.prototype
添加了一个名为 last
的方法,该方法检查数组长度,如果长度为零,则返回 -1,否则返回数组的最后一个元素。
后记:太深太多,爱会走火入魔