0

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 !

2
  • 1
    Well, you definitely don't want to assign the prototype to the result of reverse. Have you tried using this? this.reduce(function(... Commented Oct 25, 2016 at 21:40
  • Mike, it's working, :) please post your comments again as reply, so i can accept it, thanks so much ! Commented Oct 25, 2016 at 21:55

1 Answer 1

1

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

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());

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.