2619. 数组原型对象的最后一个元素

83 阅读1分钟

请你编写一段代码实现一个数组方法,使任何数组都可以调用 array.last() 方法,这个方法将返回数组最后一个元素。如果数组中没有元素,则返回 -1 。

你可以假设数组是 JSON.parse 的输出结果。

/**
* @return {any}
* 返回数组原型最后一个元素
 */

 Array.prototype.last=function(){
    if(this.length===0){
        return -1
    }else{
        return this[this.length - 1]
    }
 }
 
 
 let a = [1, 2, 3, { a: 1 }]
 console.log(a.last())