Finding an item of an array of numbers without using a loop

前端 未结 5 799
借酒劲吻你
借酒劲吻你 2021-01-03 13:05

This is a stupid question, it feels like one. But mental block is bad right now. :(

My problem is I have an array consisting only of numbers. I want to use that arra

5条回答
  •  旧时难觅i
    2021-01-03 13:27

    if (a.indexOf(2) >= 0)
    

    Note that IE < 9 doesn't have indexOf, so you'll needto add it in case it doesn't exist:

    if (!Array.prototype.indexOf)
    {
      Array.prototype.indexOf = function(searchElement /*, fromIndex */)
      {
        "use strict";
    
        if (this === void 0 || this === null)
          throw new TypeError();
    
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0)
          return -1;
    
        var n = 0;
        if (arguments.length > 0)
        {
          n = Number(arguments[1]);
          if (n !== n) // shortcut for verifying if it's NaN
            n = 0;
          else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
            n = (n > 0 || -1) * Math.floor(Math.abs(n));
        }
    
        if (n >= len)
          return -1;
    
        var k = n >= 0
              ? n
              : Math.max(len - Math.abs(n), 0);
    
        for (; k < len; k++)
        {
          if (k in t && t[k] === searchElement)
            return k;
        }
        return -1;
      };
    }
    

提交回复
热议问题