有人能告诉我如何检测“特殊词”出现在数组中吗?例子:
categories: [
"specialword"
"word1"
"word2"
]
有人能告诉我如何检测“特殊词”出现在数组中吗?例子:
categories: [
"specialword"
"word1"
"word2"
]
当前回答
我们可以使用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(索引) console.log(一些)
请核对一下。
其他回答
我不喜欢$. 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);
}
你可以使用for循环:
var found = false;
for (var i = 0; i < categories.length && !found; i++) {
if (categories[i] === "specialword") {
found = true;
break;
}
}
使用现代javascript的Array方法:
Array.prototype.includes() //在ES7中引入:
返回布尔值
Const data = { 类别:[ “specialword”, “word1”, “word2 ] } console.log(“Array.prototype.includes()”) / / Array.prototype.includes () //返回Boolean值 console.log (data.categories.includes(“specialword”)) console.log (data.categories.includes(“non-exist”)) .as-console-wrapper {max-height: 100% !重要;上图:0;}
Array.prototype.find() //在ES6中引入:
返回找到的或未定义的元素
Const data = { 类别:[ “specialword”, “word1”, “word2 ] } console.log(“Array.prototype.find()”) / / Array.prototype.find () //返回找到的元素 //如果未找到则返回undefined console.log (data.categories。Find (el => el === "specialword") != undefined) console.log (data.categories。Find (el => el === "不存在")!= undefined) .as-console-wrapper {max-height: 100% !重要;上图:0;}
你真的不需要jQuery。
var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);
提示:indexOf返回一个数字,表示指定的搜索值第一次出现的位置,如果从未出现,则返回-1 发生
or
function arrayContains(needle, arrhaystack)
{
return (arrhaystack.indexOf(needle) > -1);
}
值得注意的是,在IE < 9中不支持array.indexOf(..),但jQuery的indexOf(…)函数即使在这些旧版本中也可以工作。
给你:
$.inArray('specialword', arr)
该函数返回一个正整数(给定值的数组下标),如果在数组中没有找到给定值,则返回-1。
现场演示:http://jsfiddle.net/simevidas/5Gdfc/
你可能会这样使用它:
if ( $.inArray('specialword', arr) > -1 ) {
// the value is in the array
}