Need help regarding jQuery $.inArray()

两盒软妹~` 提交于 2019-12-11 16:46:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!