0
点赞
收藏
分享

微信扫一扫

jquery判断元素是否存在在数组中


var myArray = new Array();
function checkRepeat(sel) {
console.log("索引是:" + $.inArray(sel, myArray)); //返回索引 如果存在返回索引值,不存在返回-1
if ($.inArray(sel, myArray) >= 0) {
var msgModel = { MsgType: "warning", msg: "选择项重复", result: false, msgTitle: "系统提示" };
BPM.ShowMsg(msgModel);
return false;
} else {
myArray.push(sel);
for (i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
console.log(myArray);
}
}

$.inArray()方法类似于JavaScript的原生.indexOf()方法,没有找到匹配元素时它返回-1。如果数组第一个元素匹配value(参数) ,那么$.inArray()返回0。
因为JavaScript将0视为false(即 0 == false, 但是 0 !== false),要检查在array中是否存在value, 你需要检查它是否不等于(或大于)-1。
值之间的比较是严格比较(愚人码头注:即,===或!==比较)。下面这段代码返回 -1 (没有找到) , 因为字符串数组中不可能找到一个数字:




1






$.inArray( 5 + 5, [ "8", "9", "10", 10 + "" ] );



例子:

返回数组中指定元素的索引值。





1


2


3


4


5


6


7


8


9


10


11


12


13


14


15


16


17


18


19


20


21


22


23


24


25





<!DOCTYPE html>




<html>




<head>




<style>




div { color:blue; }




span { color:red; }




</style>




<script src="http://code.jquery.com/jquery-latest.js"></script>




</head>




<body>









<div>"John" found at <span></span></div>




<div>4 found at <span></span></div>




<div>"Karl" not found, so <span></span></div>




<div>"Pete" is in the array, but not at or after index 2, so <span></span></div>




<script>var arr = [ 4, "Pete", 8, "John" ];




var $spans = $("span");




$spans.eq(0).text(jQuery.inArray("John", arr));




$spans.eq(1).text(jQuery.inArray(4, arr));




$spans.eq(2).text(jQuery.inArray("Karl", arr));




$spans.eq(3).text(jQuery.inArray("Pete", arr, 2));




</script>









</body>




</html>







http://www.css88.com/jqapi-1.9/jQuery.inArray/











$.inArray()
.indexOf()
value
$.inArray()
array
value
-1
$.inArray( 5 + 5, [ "8", "9", "10", 10 + "" ] );
<!DOCTYPE html>
<html>
<head>
<style>
div { color:blue; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<div>"John" found at <span></span></div>
<div>4 found at <span></span></div>
<div>"Karl" not found, so <span></span></div>
<div>"Pete" is in the array, but not at or after index 2, so <span></span></div>
<script>var arr = [ 4, "Pete", 8, "John" ];
var $spans = $("span");
$spans.eq(0).text(jQuery.inArray("John", arr));
$spans.eq(1).text(jQuery.inArray(4, arr));
$spans.eq(2).text(jQuery.inArray("Karl", arr));
$spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
</script>

</body>
</html>

举报

相关推荐

0 条评论