在不使用循环的情况下查找数字数组中的一项

2022-01-17 00:00:00 arrays numbers javascript

这是一个愚蠢的问题,感觉就像一个问题.但是现在精神障碍很糟糕.:(

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

我的问题是我有一个仅由数字组成的数组.我想将该数组用作查找,但我传递给在数组中查找数字的数字一直在查找该数字的 index 中的数组,而不是该数字是否存在 /strong> 在数组中.

My problem is I have an array consisting only of numbers. I want to use that array as a lookup, but the number I pass to lookup a number in the array keeps looking to the array in the index of that number, not whether that number exists in the array.

例如:

var a = [2,4,6,8,10],
b = 2;

if(a[b]){ /* if the number 2 exists in the array a, then do something * }

但这要看位置 2 (6) 中的数组值,而不是值 2 是否在数组中.这是完全有道理的,但是(精神障碍)我无法找到一种方法来测试一个数字是否存在于一个数字数组中......我什至将所有内容都设为字符串,但它确实类型强制并且问题仍然存在.

But that looks at the array value in position 2 (6), not whether the value 2 is in the array. And this makes perfect sense, but (mental block) I can't figure out a way to test whether a number exists in an array of numbers... I even made everything strings, but it does type coercion and the problem persists.

在这里拉我的头发.请帮忙,谢谢.:D

Pulling my hair out here. Please help, thanks. :D

推荐答案

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

请注意,IE

9 没有indexOf,所以你需要添加它以防它不存在:

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;
  };
}

相关文章