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

时间:2016-10-25 21:38:19

标签: javascript

我第一次尝试编写数组原型函数。

原始问题是这个,

  1. 数组为[2,0,1,3]

  2. 返回30102,基本上将数组反转为[3,1,0,2]

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

  4. 所以我想实现一个数组函数来做到这一点

    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()方法时打印了数组)。

    请问如何解决?谢谢!

1 个答案:

答案 0 :(得分:1)

您应该将您的数组称为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());

相关问题