谁能告诉我如何检测"specialword"是否出现在一个数组中?例子。
"specialword"
categories: [ "specialword" "word1" "word2" ]
jQuery提供[$.inArray][1]。
$.inArray
注意inArray返回找到的元素的索引,所以0表示该元素是数组中的第一个。-1表示没有找到该元素。
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>
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年?!
给你。
$.inArray('specialword', arr)
该函数返回一个正整数(给定值的数组索引),如果在数组中没有找到给定值,则返回`-1'。
实时演示: http://jsfiddle.net/simevidas/5Gdfc/
你可能想这样使用它。
if ( $.inArray('specialword', arr) > -1 ) { // the value is in the array }
你可以使用一个for循环。
for
var found = false; for (var i = 0; i < categories.length && !found; i++) { if (categories[i] === "specialword") { found = true; break; } }
jQuery提供[
$.inArray
][1]。注意inArray返回找到的元素的索引,所以
0
表示该元素是数组中的第一个。-1
表示没有找到该元素。3年后再编辑。
天哪,6.5年?!
给你。
该函数返回一个正整数(给定值的数组索引),如果在数组中没有找到给定值,则返回`-1'。
实时演示: http://jsfiddle.net/simevidas/5Gdfc/
你可能想这样使用它。
你可以使用一个
for
循环。