user3552178 user3552178 - 9 months ago 43
Javascript Question

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

My first attempt to write an array prototype function.

The original issue is this,


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

  2. return 30102, basically reverse the array to be [3, 1, 0, 2]

  3. then 3*1000000 + 1 *10000 + 0*100 + 2



So i want to implement an array function to do this

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


The problem is, when i really uses it, the Array inside the implement becomes empty, (i did print the array when i use the blobArray2Int() method).

How to fix it please ? Thanks !

Answer Source

You should refer to your array as "this" instead of Array.prototype. So your code should look more like this:

Array.prototype.blobArray2Int = Array.prototype.blobArray2Int || function() {
    return this.reduceRight(function(total, num) {
                                return total*100 + num;
                            });
};

Here is a codepen showing it work