Searching a javascript array

Asked

Viewed 161 times

1

How to search within a javascript array?

The solution I use is a gambiarra.

x = ['a','b','c','d'];

if ( x.indexOf('a') != -1) {

    console.log('Verdadeiro');

} else {
    console.log('Falso');
}

2 answers

1

Jonas, the way you’re using is the historically correct way.

There is now a new way, which is already available in most browsers which is .includes() and that is part of Ecmascript 2016. With this new syntax you can use:

x = ['a','b','c','d'];

if (x.includes('a')) console.log('Verdadeiro');
else console.log('Falso');

0

It’s okay to use Array().indexOf, this is the only way to discover the index of a specific element in a Array, walking herself.

Therefore, you could make a polyfill to work on all browsers.

Edit: I had to grow the polyfill code because MSIE6 is quite a browser narrow. i++, instead of increasing the i after returning its own value, ends up returning the i incremented.

if (!Array.prototype.indexOf)

    Array.prototype.indexOf = function(item) {
        var me = this;
        /* Percore a array até achar um item igual à @item. */
        for (var i = 0, l = me.length; i < l && (me[i] === item ? false : true); i++);
        return i < l ? i : -1;
    };

Browser other questions tagged

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