LeetCode--(1)2619. 数组原型对象的最后一个元素

61 阅读1分钟

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

示例 1 :

输入: nums = [null, {}, 3]
输出: 3
解释:调用 nums.last() 后返回最后一个元素: 3。

示例 2 :

输入: nums = []
输出: -1
解释: 因为此数组没有元素,所以应该返回 -1。

 

提示:

  • arr 是一个有效的 JSON 数组
  • 0 <= arr.length <= 1000

参考方案:

/**
 * @return {null|boolean|number|string|Array|Object}
 */
 const arr = [1, 2, 3]
Array.prototype.last = function() {
    if(this.length>0){
        return this[this.length-1]
    }else{
        return -1
    }
};
console.log(arr.last())
/**
 * const arr = [1, 2, 3];
 * arr.last(); // 3
 */

方案提示:

在代码中, this 指向 arr 数组,是因为将 last 方法添加到了 Array.prototype 原型上,而在 JavaScript 中,原型方法中的 this 指向调用该方法的对象。 调用 arr.last() 时, last 方法被作为 arr 数组的方法调用,因此在该方法内部, this 指向了 arr 数组对象。

这样做的好处是 可以在数组对象上添加自定义方法,以扩展数组的功能。通过将方法添加到原型上,所有的数组实例都可以使用该方法。 需要注意的是,在使用 this 时要确保正确的上下文。如果你在箭头函数中使用 this ,它将继承外部作用域的 this 值,而不是指向调用对象。

总结起来, this 的指向是动态的,取决于函数或方法的调用方式。在你的代码中, this 指向了调用 last 方法的数组对象 arr

LeetCode运行:

leetcode.cn/problems/ar…