JavaScript 在数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5864408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:14:51  来源:igfitidea点击:

JavaScript is in array

javascript

提问by test

Let's say I have this:

假设我有这个:

var blockedTile = new Array("118", "67", "190", "43", "135", "520");

There's more array elements but those are just few for readability purposes. Anyways, I could do a "for" loop but it would do 500 loops everytime you click on the map... is there any other way to see if a certain string is in an array?

有更多的数组元素,但出于可读性目的,这些元素很少。无论如何,我可以做一个“for”循环,但每次点击地图时它都会做 500 次循环……有没有其他方法可以查看某个字符串是否在数组中?

回答by Bala R

Try this:

尝试这个:

if(blockedTile.indexOf("118") != -1)
{  
   // element found
}

回答by Kutyel

As mentioned before, if your browser supports indexOf(), great! If not, you need to pollyfil it or rely on an utility belt like lodash/underscore.

如前所述,如果您的浏览器支持indexOf(),那就太好了!如果没有,您需要对其进行 pollyfil 或依赖实用工具带,如lodash/underscore

Just wanted to add this newer ES2016addition (to keep this question updated):

只是想添加这个较新的ES2016补充(以保持这个问题的更新):

Array.prototype.includes()

Array.prototype.includes()

if (blockedTile.includes("118")) {
    // found element
}

回答by ndhanhse

function in_array(needle, haystack){
    var found = 0;
    for (var i=0, len=haystack.length;i<len;i++) {
        if (haystack[i] == needle) return i;
            found++;
    }
    return -1;
}
if(in_array("118",array)!= -1){
//is in array
}

回答by Brandon Boone

Use Underscore.js

使用Underscore.js

It cross-browser compliantand can perform a binary search if your data is sorted.

跨浏览器兼容,如果您的数据已排序,则可以执行二进制搜索。

_.indexOf

_。指数

_.indexOf(array, value, [isSorted]) Returns the index at which value can be found in the array, or -1 if value is not present in the array. Uses the native indexOf function unless it's missing. If you're working with a large array, and you know that the array is already sorted, pass true for isSorted to use a faster binary search.

_.indexOf(array, value, [isSorted]) 返回可以在数组中找到值的索引,如果数组中不存在值,则返回 -1。使用本机 indexOf 函数,除非它丢失。如果您正在处理一个大数组,并且您知道该数组已经排序,请为 isSorted 传递 true 以使用更快的二进制搜索。

Example

例子

//Tell underscore your data is sorted (Binary Search)
if(_.indexOf(['2','3','4','5','6'], '4', true) != -1){
    alert('true');
}else{
    alert('false');   
}

//Unsorted data works to!
if(_.indexOf([2,3,6,9,5], 9) != -1){
    alert('true');
}else{
    alert('false');   
}

回答by alex

Some browsers support Array.indexOf().

一些浏览器支持Array.indexOf().

If not, you could augment the Arrayobject via its prototype like so...

如果没有,你可以Array通过它的原型来增强对象,就像这样......

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

Source.

来源

回答by Сергей Савельев

Just use for your taste:

只为您的口味使用:

var blockedTile = [118, 67, 190, 43, 135, 520];

// includes (js)

if ( blockedTile.includes(118) ){
    console.log('Found with "includes"');
}

// indexOf (js)

if ( blockedTile.indexOf(67) !== -1 ){
    console.log('Found with "indexOf"');
}

// _.indexOf (Underscore library)

if ( _.indexOf(blockedTile, 43, true) ){
    console.log('Found with Underscore library "_.indexOf"');
}

// $.inArray (jQuery library)

if ( $.inArray(190, blockedTile) !== -1 ){
    console.log('Found with jQuery library "$.inArray"');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

回答by Marty

if(array.indexOf("67") != -1) // is in array

回答by Alex Under

Best way to do it in 2019 is by using .includes()

2019 年最好的方法是使用 .includes()

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(1, 2);  // false

First parameter is what you are searching for. Second parameter is the index position in this array at which to begin searching.

第一个参数是您要搜索的内容。第二个参数是该数组中开始搜索的索引位置。

If you need to be crossbrowsy here - there are plenty of legacy answers.

如果您需要在这里浏览 - 有很多遗留答案。

回答by Krunal Limbad

Already answered above but wanted to share.

上面已经回答了,但想分享。

Will not work in IE though. thanks for mentioning it @Mahmoud

虽然不会在 IE 中工作。感谢您提及@Mahmoud

var array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

var pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

got some reference Here. they also have Polyfill for above.

这里得到了一些参考。他们还有上面的 Polyfill。

回答by Mark Giblin

IMHO most compatible with older browsers

恕我直言,与旧浏览器最兼容

Array.prototype.inArray = function( needle ){

    return Array(this).join(",").indexOf(needle) >-1;

}

var foods = ["Cheese","Onion","Pickle","Ham"];
test = foods.inArray("Lemon");
console.log( "Lemon is " + (test ? "" : "not ") + "in the list." );

By turning an Array copy in to a CSV string, you can test the string in older browsers.

通过将 Array 副本转换为 CSV 字符串,您可以在旧浏览器中测试该字符串。