问题
Could anybody tell me what is wrong with this code ??
jQuery(document).ready(function(){
var val = ["Hourly", "Daily", "Weekly", "Monthly", "Yearly"];
var myArr = ["Weekly", "something"];
$( myArr ).each(function( j ){
if ( $.inArray( myArr[j] == val ) ) {
alert( 'yes, Matched !!' );
console.log( myArr[j] );
} else {
alert( 'Nops ' );
}
});
//console.log( val );
});
I need to match the array elements, i used $.inArray()
, but it never goes to ELSE condition even it doesn't exist in the array.
Any help would be appreciatd.
回答1:
$.inArray() takes two arguments, the value and the array, and returns > -1
if it finds a match, so it should be like this:
jQuery(document).ready(function(){
var val = ["Hourly", "Daily", "Weekly", "Monthly", "Yearly"];
var myArr = ["Weekly", "something"];
$.each(myArr, function(i, v) {
if ($.inArray(v, val) != -1) {
alert( 'yes, Matched !!' );
console.log(v);
} else {
alert( 'Nops ' );
}
});
});
You can test it here. Also note the use of $.each() for non-element sets, no reason creating an invalid jQuery object to run the loop.
回答2:
jQuery(document).ready(function() {
var val = ["Hourly", "Daily", "Weekly", "Monthly", "Yearly"];
var myArr = ["Weekly", "something"];
$(myArr).each(function(j) {
if ($.inArray(myArr[j], val) != -1) {
alert('yes, Matched !!');
} else {
alert('Nops ');
}
});
});
$.inArray
returns -1
when it doesn't find the value in the array, otherwise it returns the position in the array, which could be 0
.
来源:https://stackoverflow.com/questions/4169106/need-help-regarding-jquery-inarray