Javascript testing if the value is in an array

Is there a function in javascript for this - check if the given value exists in the array (of strings) (string in my case)? I know that I can just iterate over each value, but I wonder if js has a shorthand for that.

+3
source share
3 answers

jquery has . inArray () method, This is the best I know.

+3
source

Here .indexOf(), but IE <9 does not support it:

if(array.indexOf("mystring") > -1) {
  //found
}

From the same MDC documentation page , here's what to enable (before use) for IE to work as well:

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

.indexOf() , , -1, .

+2

For functions that are in php and should be in javascript, or I haven't found one yet, I go: http://phpjs.org

The function you want to use if you just use javascript is here in_array: http://phpjs.org/functions/in_array:432

Otherwise, use the jQuery solution on this page.

0
source

Source: https://habr.com/ru/post/1767528/


All Articles