[英]JS How to make a new method to an Array using prototype but with a function that takes no parameters
我想用一個名為 square() 的新方法擴展數組,該方法返回一個所有數字平方的新數組。 我嘗試制作它,但我無法弄清楚該函數不采用任何參數(如默認的 JS Array methods )的方法。 例如array.reverse()
返回數組反轉它不以數組作為參數,像這樣: array.reverse(array)
這是我的代碼:
Array.prototype.square = function(Array){
let a = []
for (let num of Array){
a.push(num**2)
}
return a
}
您可以在函數內部使用this
關鍵字,它將引用調用它的數組。
Array.prototype.square = function() { return this.map(number => number ** 2) } let test = [1, 2, 3] console.log(test.square())
您走在正確的軌道上,可以像這樣輕松完成:
Array.prototype.square = function () {
return this.map((number) => number * number)
}
let a = [1, 2]; // sample array
console.log(a.square()); // prints [1, 4]
我使用了地圖,這使得這個過程非常簡單。 有關更多信息,請參閱此: 數組映射函數
作為記錄...
(這種添加方法的名稱稱為包裝器)
/* --- Array.square wrapper--- */ if (!Array.prototype.square) // check that the square method does not already exist { Array.prototype.square = function(){ return this.map(x=>x**2) } } let arr1 = [1,2,3,5,7] , arr2 = arr1.square() ; console.log('arr1 ->', JSON.stringify( arr1 )) console.log('arr2 ->', JSON.stringify( arr2 ))
當您向原型添加方法時,對象/數組將始終是this
上下文。 所以你可以簡單地循環this
。
(旁白:檢查該方法是否已經存在於原型中通常很好,這也是我也包含該代碼的原因。)
if (!('square' in Array.prototype)) { Array.prototype.square = function() { const arr = []; for (let i = 0; i < this.length; i++) { arr.push(this[i] ** 2); } return arr; } } console.log([1, 2, 3].square());
或者,更簡單地說,使用map
返回一個新數組。
if (!('square' in Array.prototype)) { Array.prototype.square = function() { return this.map(el => el ** 2); } } console.log([1, 2, 3].square());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.