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

发布于 2024-11-09 08:50:51 字数 142 浏览 0 评论 0原文

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

categories: [
    "specialword"
    "word1"
    "word2"
]

Can someone tell me how to detect if "specialword" appears in an array? Example:

categories: [
    "specialword"
    "word1"
    "word2"
]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

指尖凝香 2024-11-16 08:50:51

你确实不需要 jQuery 来做这个。

var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);

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

function arrayContains(needle, arrhaystack)
{
    return (arrhaystack.indexOf(needle) > -1);
}

值得注意的是 array.indexOf(..)IE 不支持 < 9,但 jQuery 的 indexOf(...) 函数甚至适用于那些旧版本。

You really don't need jQuery for this.

var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);

Hint: indexOf returns a number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never
occurs

or

function arrayContains(needle, arrhaystack)
{
    return (arrhaystack.indexOf(needle) > -1);
}

It's worth noting that array.indexOf(..) is not supported in IE < 9, but jQuery's indexOf(...) function will work even for those older versions.

最美的太阳 2024-11-16 08:50:51

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
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


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


3 年后再次编辑

天哪,6.5 年?!

在现代 JavaScript 中,最好的选择是 Array.prototype.includes()

const found = categories.includes('specialword');

没有比较,没有混淆 -1 结果。它执行我们想要的操作:返回 truefalse。对于旧版浏览器,它是polyfillable,使用代码位于MDN

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

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

console.log(foundPresent, foundNotPresent); // true false

jQuery offers $.inArray:

Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.

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
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Edit 3.5 years later

$.inArray is effectively a wrapper for Array.prototype.indexOf in browsers that support it (almost all of them these days), while providing a shim in those that don't. It is essentially equivalent to adding a shim to Array.prototype, which is a more idiomatic/JSish way of doing things. MDN provides such code. These days I would take this option, rather than using the jQuery wrapper.

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


Edit another 3 years later

Gosh, 6.5 years?!

The best option for this in modern JavaScript is Array.prototype.includes():

const found = categories.includes('specialword');

No comparisons and no confusing -1 results. It does what we want: it returns true or false. For older browsers it's polyfillable using the code at MDN.

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

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

console.log(foundPresent, foundNotPresent); // true false

旧瑾黎汐 2024-11-16 08:50:51

在这里:

$.inArray('specialword', arr)

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

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

您可能想使用像这样:

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

Here you go:

$.inArray('specialword', arr)

This function returns a positive integer (the array index of the given value), or -1 if the given value was not found in the array.

Live demo: http://jsfiddle.net/simevidas/5Gdfc/

You probably want to use this like so:

if ( $.inArray('specialword', arr) > -1 ) {
    // the value is in the array
}
凉月流沐 2024-11-16 08:50:51

我们可以使用 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)

请检查这个。

we can use includes option (which is js built-in function), which will return true if the value is found else it will be false.

if you want the exact index you can use indexOf (which is also js built-in function), which will return the exact index if the value is found else it will return -1.

You can switch .includes with the .some method which returns a boolean.
It will exit as soon as a match was found, which is great for performance for huge arrays:

Note: all are case sensitive

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)

please check this.

冷…雨湿花 2024-11-16 08:50:51

您可以使用 for 循环:

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

You can use a for loop:

var found = false;
for (var i = 0; i < categories.length && !found; i++) {
  if (categories[i] === "specialword") {
    found = true;
    break;
  }
}
薆情海 2024-11-16 08:50:51

使用现代 javascript 的 Array 方法:

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"))
.as-console-wrapper { max-height: 100% !important; top: 0; }

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)
.as-console-wrapper { max-height: 100% !important; top: 0; }

With modern javascript's Array methods:

Array.prototype.includes() // introduced in ES7:

  • returns boolean

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"))
.as-console-wrapper { max-height: 100% !important; top: 0; }

Array.prototype.find() // introduced in ES6:

  • returns found element or undefined

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)
.as-console-wrapper { max-height: 100% !important; top: 0; }

情话已封尘 2024-11-16 08:50:51

我不喜欢 $.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;
}

同样,您可以将 $.inArray 包装在扩展中:

$.fn.contains = function (target) {
  return ($.inArray(target, this) > -1);
}

I don't like $.inArray(..), it's the kind of ugly, jQuery-ish solution that most sane people wouldn't tolerate. Here's a snippet which adds a simple contains(str) method to your arsenal:

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

Similarly, you could wrap $.inArray in an extension:

$.fn.contains = function (target) {
  return ($.inArray(target, this) > -1);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文