admin管理员组文章数量:1126112
Can someone tell me how to detect if "specialword"
appears in an array? Example:
categories: [
"specialword"
"word1"
"word2"
]
Can someone tell me how to detect if "specialword"
appears in an array? Example:
categories: [
"specialword"
"word1"
"word2"
]
Share
Improve this question
edited Nov 8, 2017 at 15:36
Cofey
asked May 24, 2011 at 20:31
CofeyCofey
11.4k16 gold badges54 silver badges75 bronze badges
5
- In pure JS: stackoverflow.com/a/25765186/1320932 – dr.dimitru Commented Sep 10, 2014 at 12:19
- 36 pure JS : categories.includes("specialword") – patz Commented Apr 12, 2016 at 17:50
- 4 @patz watch out for pure JS, not supported in IE (any version) link – foxontherock Commented Dec 12, 2017 at 15:29
- @foxontherock start using transpiler - stop worrying about anything fact-checking, can-I-use-this-property kinda thing. – Alex Pogiba Commented Aug 23, 2018 at 6:52
- Does this answer your question? How do I check if an array includes a value in JavaScript? – gre_gor Commented May 3, 2023 at 18:20
7 Answers
Reset to default 1168 +500You 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.
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
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
}
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.
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;
}
}
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; }
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);
}
本文标签: How to find if an array contains a specific string in JavaScriptjQueryStack Overflow
版权声明:本文标题:How to find if an array contains a specific string in JavaScriptjQuery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736681442a1947442.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论