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

How to use Array functions inside my own Array prototype function?

本文关键字:函数 数组 原型 我自己 自己的      更新时间:2023-09-26

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

原文是这样的,

  1. array is [2,0,1,3]

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

  3. then 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;
}

问题是,当我真正使用它时,实现内部的Array变为空,(当我使用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());