如何查找如果数组包含使用JavaScript / jQuery的一个特定的字符串? [英] How to find if an array contains a specific string in JavaScript/jQuery?

查看:95
本文介绍了如何查找如果数组包含使用JavaScript / jQuery的一个特定的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 类别:
    specialword
    字词1
    WORD2
]


解决方案

jQuery提供 $ .inArray

  VAR找到= $ .inArray('specialword',类别)> -1;

注意inArray返回找到的元素的索引,所以 0 表示该元素是数组中的第一个。 1 表示元素没有被发现。


编辑5年后

$。inArray 实际上是在支持它的浏览器为 Array.prototype.indexOf 包装(几乎所有的他们这些天),而在那些提供一个垫片不这样做。它本质上是相当于增加一个垫片,以 Array.prototype ,这是一个做事的更地道/ JSish方式。 MDN提供<一个href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill\"相对=nofollow>例如code 。这些天,我会采取这个选项,而不是使用jQuery的包装。

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

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

解决方案

jQuery offers $.inArray:

var found = $.inArray('specialword', categories) > -1;

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.

Example.


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.

这篇关于如何查找如果数组包含使用JavaScript / jQuery的一个特定的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆