一、解析
数组本身没有last这个方法,需要我们自己手动实现,并挂载到数组的原型上,供所有实例共享。在实现过程中,需要判断当前数组长度大小来决定返回内容,长度为0返回-1,不为0返回数组的最后一个元素。
二、代码
1.使用三元运算符
Array.prototype.last = function () {
// this 指向当前数组实例
return this.length ? this[this.length-1]:-1;
}
let arr = [1,2,3];
let arr2 = []
console.log(arr.last()); // 3
console.log(arr2.last()); // -1
2.使用if语句
Array.prototype.last = function () {
if (this.length === 0) {
return -1;
} else {
return this[this.length-1];
}
}
let arr = [1,2,3];
let arr2 = []
console.log(arr.last()); // 3
console.log(arr2.last()); // -1
三、注意
- JSON数组是指数组内的元素类型不限,可以是基本数据类型,也可以是引用数据类型。
- 由于数组长度是判断要素,所以不能使用空值合并运算符(??),此运算符只有当做测试null或undefined才返回右侧值,否则返回左侧值。