簡體   English   中英

如何在我自己的Array原型函數中使用Array函數?

[英]How to use Array functions inside my own Array prototype function?

我第一次嘗試編寫數組原型函數。

原來的問題是這樣的,

  1. 數組是[2,0,1,3]

  2. 返回30102,基本上將數組反轉為[3,1,0,2]

  3. 然后3 * 1000000 +1 * 10000 + 0 * 100 + 2

所以我想實現一個數組函數來做到這一點

Array.prototype.blobArray2Int
    = Array.prototype.blobArray2Int || function() {

    //Array.prototype.reverse();
    Array.prototype = Array.prototype.reverse();
    cnt = Array.prototype.reduce(function(total, num) {
                                return total*100 + num;
                            });
    return cnt;
}

問題是,當我真正使用它時,工具內的數組會變空((當我使用blobArray2Int()方法時,確實打印了數組)。

請如何解決? 謝謝 !

您應該使用this數組代替Array.prototype 因此,您的代碼應更像這樣:

 var a = new Array(2, 0, 1, 3); Array.prototype.blobArray2Int = Array.prototype.blobArray2Int || function() { return this.reduceRight(function(total, num) { return total * 100 + num; }); }; document.write(a.blobArray2Int()); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM