題目
請你編寫一段代碼實(shí)現(xiàn)一個(gè)數(shù)組方法,使任何數(shù)組都可以調(diào)用 array.last()
方法,這個(gè)方法將返回?cái)?shù)組最后一個(gè)元素。如果數(shù)組中沒有元素,則返回 -1
。
你可以假設(shè)數(shù)組是 JSON.parse
的輸出結(jié)果。
示例 1 :
輸入:nums = [null, {}, 3]
輸出:3
解釋:調(diào)用 nums.last() 后返回最后一個(gè)元素: 3
。
示例 2 :
輸入:nums = []
輸出:-1
解釋:因?yàn)榇藬?shù)組沒有元素,所以應(yīng)該返回 -1
。
提示:
arr
是一個(gè)有效的 JSON
數(shù)組
0 <= arr.length <= 1000
題解
在定義
Array
類共用方法時(shí),函數(shù)內(nèi)的this
代表本數(shù)組文章來源:http://www.zghlxwxcb.cn/news/detail-812726.html
declare global {
interface Array<T> {
last(): T | -1;
}
}
Array.prototype.last = function<T>(): T | -1 {
let list: T[] = [...this];
if (!list.length) return -1;
return list[list.length -1]
};
/**
* const arr = [1, 2, 3];
* arr.last(); // 3
*/
export {};
文章來源地址http://www.zghlxwxcb.cn/news/detail-812726.html
到了這里,關(guān)于【LeetCode】2619. 數(shù)組原型對象的最后一個(gè)元素的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!