开发者

javascript testing if value is in array

开发者 https://www.devze.com 2023-01-18 21:01 出处:网络
Is there a function in javascript to do this - test if a given value (a string in my case) exists in an array (of strings)?I know I could just loop over each value, but I\'m wondering if js has a shor

Is there a function in javascript to do this - test if a given value (a string in my case) exists in an array (of strings)? I know I could just loop over each value, but I'm wondering if js has a short开发者_开发技巧hand for this.


jquery has .inArray() method. It's the best I know..


There's .indexOf() for this, but IE<9 doesn't support it:

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

From the same MDC documentation page, here's what to include (before using) to make IE 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() returns the index in the array the string was found at, or -1 if it wasn't found.


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

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

Otherwise, use the jQuery solution on this page.

0

精彩评论

暂无评论...
验证码 换一张
取 消