如何在JavaScript/jQuery中查找数组是否包含特定字符串?

Cof*_*fey 570 javascript arrays string jquery

有人能告诉我如何检测是否"specialword"出现在数组中?例:

categories: [
    "specialword"
    "word1"
    "word2"
]
Run Code Online (Sandbox Code Playgroud)

Jam*_*mes 901

你真的不需要jQuery.

var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);
Run Code Online (Sandbox Code Playgroud)

提示:indexOf返回一个数字,表示第一次发生指定搜索值的位置,如果从未发生,则返回-1

要么

function arrayContains(needle, arrhaystack)
{
    return (arrhaystack.indexOf(needle) > -1);
}
Run Code Online (Sandbox Code Playgroud)

值得注意的array.indexOf(..)IE <9不支持,但jQuery的indexOf(...)功能甚至可以用于那些旧版本.

  • indexOf适用于所有主流浏览器,IE <9除外 (20认同)
  • @SuperUberDuper:检查是否存在对象键:`[1]中的'1' - > false`` ['a'中的'1','b'] - > true``'length'in [] - > true `就像在JS中发生的那样,数组本质上是一个带有数字键的对象. (3认同)
  • 詹姆斯,正如我所指出的那样,该页确实说它将在IE9中运行.你有没有为IE <9工作?我相信我在IE7和IE8中遇到了这个功能,但实际上没有测试; 相反,我依靠https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Browser_compatibility (2认同)
  • arr 中的“foo”怎么样? (2认同)
  • http://needsmorejquery.com (2认同)

lon*_*day 601

jQuery提供$.inArray:

请注意,inArray返回找到的元素的索引,因此0表示该元素是数组中的第一个元素.-1表示未找到该元素.

var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];

var foundPresent = $.inArray('specialword', categoriesPresent) > -1;
var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;

console.log(foundPresent, foundNotPresent); // true false
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)


3.5年后编辑

$.inArray实际上是Array.prototype.indexOf支持它的浏览器的包装器(现在几乎所有这些都是),而在那些没有支持的浏览器中提供垫片.它本质上相当于添加一个垫片Array.prototype,这是一种更惯用/ JSish的做事方式.MDN提供此类代码.这些天我会采用这个选项,而不是使用jQuery包装器.

var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];

var foundPresent = categoriesPresent.indexOf('specialword') > -1;
var foundNotPresent = categoriesNotPresent.indexOf('specialword') > -1;

console.log(foundPresent, foundNotPresent); // true false
Run Code Online (Sandbox Code Playgroud)


3年后再编辑

天哪,6.5年?!

现代Javascript中最好的选择是Array.prototype.includes:

var found = categories.includes('specialword');
Run Code Online (Sandbox Code Playgroud)

没有比较,也没有令人困惑的-1结果.它做我们想要的:它返回truefalse.对于较旧的浏览器,它可以使用MDN中的代码进行多播.

var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];

var foundPresent = categoriesPresent.includes('specialword');
var foundNotPresent = categoriesNotPresent.includes('specialword');

console.log(foundPresent, foundNotPresent); // true false
Run Code Online (Sandbox Code Playgroud)

  • 好吧,我猜你总是坚持不停地维持这个答案.@lonesomeday (7认同)

Sel*_*thi 35

我们可以使用includes选项(这是js内置函数),如果找到该值将返回true,否则将返回false。

如果你想要精确的索引,你可以使用indexOf(这也是js内置函数),如果找到该值,它将返回精确的索引,否则它将返回-1。

您可以使用返回布尔值的.some方法切换.includes 。一旦找到匹配它就会退出,这对于大型数组的性能非常有用:

注意:全部区分大小写

var myarr = ["I", "like", "turtles"];

isVal = myarr.includes('like')
index = myarr.indexOf('like')
some = myarr.some(item => item.toLowerCase() == 'like'.toLowerCase())


console.log(isVal)
console.log(index)
console.log(some)
Run Code Online (Sandbox Code Playgroud)

请检查这个。


Šim*_*das 32

干得好:

$.inArray('specialword', arr)
Run Code Online (Sandbox Code Playgroud)

此函数返回一个正整数(给定值的数组索引),或者-1如果在数组中找不到给定值.

现场演示: http ://jsfiddle.net/simevidas/5Gdfc/

您可能希望像这样使用它:

if ( $.inArray('specialword', arr) > -1 ) {
    // the value is in the array
}
Run Code Online (Sandbox Code Playgroud)


Jar*_*Par 15

你可以使用一个for循环:

var found = false;
for (var i = 0; i < categories.length && !found; i++) {
  if (categories[i] === "specialword") {
    found = true;
    break;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我可能完全错了,但你不想在for循环中声明我吗?如果你没有把"var"放在前面,它会将它放在全局上下文中(我认为......),这可能不是你想要的. (17认同)
  • 虽然这是真的,但这真的不是他在这里说的话.一些树木不要忽视森林. (7认同)
  • @ChrisJones鉴于JS-amateurs会将这个答案复制并粘贴到他们的代码中,它应该越好 (3认同)

ABD*_*NOV 14

使用现代 javascript 的数组方法:

Array.prototype.includes() // ES7 中引入:

  • 返回布尔值

const data = {
  categories: [
    "specialword",
    "word1",
    "word2"
  ]
}

console.log("Array.prototype.includes()")
// Array.prototype.includes()
// returns boolean
console.log(data.categories.includes("specialword"))
console.log(data.categories.includes("non-exist"))
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)

Array.prototype.find() // ES6 中引入:

  • 返回找到的元素或未定义的元素

const data = {
  categories: [
    "specialword",
    "word1",
    "word2"
  ]
}

console.log("Array.prototype.find()")
// Array.prototype.find()
// returns the element if found
// returns undefined if not found
console.log(data.categories.find(el => el === "specialword") != undefined)
console.log(data.categories.find(el => el === "non-exist") != undefined)
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)


Ada*_*lin 5

我不喜欢$.inArray(..),这是大多数理智的人都无法容忍的那种类似于jQuery的丑陋解决方案。这是一个片段,contains(str)为您的武器库添加了一种简单的方法:

$.fn.contains = function (target) {
  var result = null;
  $(this).each(function (index, item) {
    if (item === target) {
      result = item;
    }
  });
  return result ? result : false;
}
Run Code Online (Sandbox Code Playgroud)

同样,您可以包装$.inArray扩展名:

$.fn.contains = function (target) {
  return ($.inArray(target, this) > -1);
}
Run Code Online (Sandbox Code Playgroud)

  • (我不是拒绝投票的人)我不确定我是否在包装依赖于$(selector).each()的方法时理解$ .inArray的嘲笑。实际的inArray代码仅将indexOf用于本机支持它的浏览器,或者使用不支持Jared的for循环(如不支持)的浏览器。对我来说似乎很优雅。 (6认同)