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>
浙公网安备 33010602011771号