流浪のwolf

卷帝

导航

7-11 leetcode 2619

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

ps:this 环境变量的使用 ,this.length 的返回值是数字类型

代码实现:

 <script>
        //在数组的原型写扩展方法可以给所有的数组一起使用 
        Array.prototype.last = function() {
            if(this.length === 0) return -1
            return this[this.length - 1]
        };

        const arr = []
        const a = arr.last()
        console.log(a)

     </script>

 

posted on 2023-07-11 22:43  流浪のwolf  阅读(5)  评论(0编辑  收藏  举报