[英]How can I map a prototype function to an array of objects that have that prototype?
[英]How can I return the array object from Array's prototype function?
我有一個編程練習來創建兩個Array的原型,它們都是函數。 我把我的代碼放在下面。 一個將在另一個上調用,如最后一行所示。 我試圖讓第二個函數修改通過簡單地調用第一個函數返回的值。 這是針對下面的代碼,我希望輸出為[4,6,4000],而我在推送后得到數組的長度,即在這種情況下為3。
Array.prototype.toTwenty = function()
{
return [4,6];
};
Array.prototype.search = function (lb)
{
if(lb >2)
{
//This doesn't work
return this.push(4000);
}
};
var man = [];
console.log(man.toTwenty().search(6));
//console.log returns 3, I need it to return [4,6,4000]
我的搜索引導我到arguments.callee.caller
但沒有嘗試,因為它被棄用,我不能使用它。
請有人幫幫我嗎? 我試圖閱讀原型繼承,鏈接和級聯,但似乎無法提取答案。 謝謝你的幫助
在Array.prototype.push
上引用MDN,
push()
方法將一個或多個元素添加到數組的末尾,並返回數組的新長度。
所以, this.push(4000)
實際上會推送值,但是當你返回push
的結果時,你得到的數組的當前長度為3
。
相反,您應該返回數組對象本身,就像這樣
Array.prototype.toTwenty = function () {
return [4, 6];
};
Array.prototype.search = function (lb) {
if (lb > 2) {
this.push(4000); // Don't return here
}
return this; // Return the array object itself.
};
console.log([].toTwenty().search(6));
// [ 4, 6, 4000 ]
我就是這樣做的,
<script>
Array.prototype.toTwenty = function() {
return [4, 6];
};
Array.prototype.search = function(lb) {
if (lb > 2) {
return this.push(4000);
}
};
var man = [];
man = man.toTwenty();
man.search(8);
console.log(man);
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.