Thomas Christopher Davies Thomas Christopher Davies - 1 month ago 8
Javascript Question

prototype returning [function] instead of Array

I am creating a prototype function for Number. As soon as I call it i get [Function] returned or the body of my function. I wonder what I did wrong. Help is appreciated.

Number.prototype.splitDigits = function(){
var str = this.toString;
var arrayDigits = [];
var length = str.length;
for (var i = 0; i<length; i++){
arrayDigits.push(Number(str.charAt(i)));
}
return arrayDigits;
};


I am calling the function like this:

var num = 2000;
var array = num.splitDigits;


What I am getting in return is:

[Function]


or

a0 function (){
var str = this.toString;
var arrayDigits = [];
var length = str.length;
for (var i = 0; i<length; i++){
arrayDigits.push(Number(str.charAt(i)));
}
return arrayDigits;
}

Answer

Two faults in your code.

  1. this.toString -> this.toString()
  2. splitDigits -> splitDigits()

After fix

Number.prototype.splitDigits = function(){
    var str = this.toString();
    var arrayDigits = [];
    var length = str.length;
    for (var i = 0; i<length; i++){
        arrayDigits.push(Number(str.charAt(i)));
    }
    return arrayDigits;
};

Run

> var num = 2000;
> var array = num.splitDigits();
> array
[2, 0, 0, 0]
Comments