2015-06-14 68 views
3

我有一個編程練習來創建兩個數組原型,它們都是函數。我已經把我的代碼放在下面。如最後一行所示,另一個將被調用。我想獲得第二個函數來修改通過簡單地調用第一個函數返回的值。這是對於下面的代碼,我希望輸出是[4,6,4000],我反過來得到推後數組的長度,即在這種情況下,3。如何從Array的原型函數返回數組對象?

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,但沒有嘗試做爲所被取消,我無法使用它。

請問有人可以幫我嗎?我試圖讀取原型繼承,鏈接和級聯,但似乎無法提取答案。感謝您的幫助

+0

*「我有一個編程練習創建兩個數組原型「*您的任務是將函數添加到'Array.prototype',而不是創建兩個p Array的旋轉型(這是不可能的)。 –

+0

1.沒有理由''toTwenty'應該放在'Array.prototype'上,因爲它不使用數組,它只是返回一個新數組。它應該在'Array'上。 2.如果要添加到'Array.prototype',最好使用'Object.defineProperty'並使添加不可枚舉。爲什麼在[這個答案]中間接覆蓋(http://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript/9329476#9329476)。 –

回答

6

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 ] 
0

這是我會怎麼做,

<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> 

Here is a demo

+0

我的代碼正在通過測試驅動開發進行評估(我剛剛在三天前解釋了這個術語!)。我必須創建將在toTwenty()。search()格式中調用的代碼,但不幸的是我無法改變它。 –