Search code examples
javascriptarraysextend

Return only array data without return the function itself using Array.prototype


I'm writing a function to do some data filtering. I write this:

Array.prototype.keyFilter = function ()
{
    var dta = this;

    for ( i in dta )
    {
        console.log( dta[i] );
    };
};

console.log( ['green','yellow','blue'].keyFilter('type') );

And the return is:

green
yellow
blue
function ()
    {
        var dta = this;

        for ( i in dta )
        {
            console.log( dta[i] );
        };
    }
undefined

OK, I get the array data ...PLUS the function itself and an "undefined". How to get only the array data using Array.prototype ??

Thanks for any help.


Solution

  • You're using for...in, which iterates over the enumerable properties of the object, including the function you've added to the prototype. That is expressly not how you're meant to iterate over arrays.

    If you want to iterate over an array, you should use a simple for loop, and count from 0 to length - 1...

    for (var i = 0; i < this.length; ++i) {
      console.log(this[i]);
    }
    

    Or, use forEach:

    this.forEach(function (i) {
      console.log(i);
    });
    

    The "undefined" part is your outer console.log(...) logging the return value of your function, which is undefined because you don't return anything.