How to access the array in an extended Javascript function

Asked

Viewed 36 times

0

Hello, I’m doing a class extension Array where I want to create a method that checks whether a property exists within the Array: thus:

Array.prototype.contains = function(element){

    for(let e of this)
        if(e === element)
            return true;

    return false;

}

The problem is that I cannot access the object of the Array instance when using this method:

[1,2,3,4].contains(3); // deveria retornar true

what I need to do to access the instance of the array in this situation?

  • 2

    console.log([1,2,3,4].contains(3)); is returning true.

  • hm... huh I got it at the time to write here unintentionally? kkk

  • I seem to have solved the problem by writing my code here... the solution is the one already described as @Sam said

1 answer

3


This is not even the answer to the problem, which turned out to be not a problem, but I will recommend not declaring prototype that way, as you will end up creating an enumerated property.

Try to do

for (let key in ['a', 'b', 'c']) {
    console.log(key);
}

You will receive 0, 1, 2 and "contains".

To create nonenumerable properties, declare them in this way:

Object.defineProperty(Array.prototype, 'contains', {
    value: function(element) {
        for(let e of this)
            if(e === element)
                return true;

        return false;
    }
});

I will also note that Javascript already has a "contains method"

[1, 2, 3, 4].includes(3);
//true
  • Um, I really didn’t know about include much less that way of declaring unlisted properties. thank you very much for the reply... I will definitely start using this form of work...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.