Easy
Write code that enhances all arrays such that you can call the array.last()
method on any array and it will return the last element. If there are no elements in the array, it should return -1
.
You may assume the array is the output of JSON.parse
.
編寫增強所有陣列的程式碼,以便在任何陣列都可以呼叫 array.last()
方法,並且所有它將回傳該陣列最後一個元素。
如果陣列中沒有元素,則應傳回 -1
。
可以假設該陣列是 JSON.parse
的輸出。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};
const person = new Person("John", 30);
person.sayHello();
// Hello, my name is John and I am 30 years old.
//為陣列原型添加一個擴充方法
Array.prototype.last = function() {
//如果數組中沒有元素,則應返回 -1
if(this.length==0){ return -1;}
//預設返回最後一個元素
return this[this.length-1]
};
let nums = [null, {}, 3]
console.log(nums.last())
//output:3
nums = []
console.log(nums.last())
//output:-1