开发者

jQuery $.inArray() returns 0

if you have 开发者_开发技巧a array like ('a', 'b') and check $.inArray('a', thearray); you get the index, which is 0, and could be false. So you need to check the result further and it's annoying...

Is there a quick method trough which I can get only true/false, and not the indexes?

basically I have a string in a html5 data attribute: data-options="a,b,c" and 3 a, b, c variables in javascript that must take true/false values based on what's inside data-options...


You can achieve that by invoking the binary NOT operator.

if( ~$.inArray('a', thearray) ) {
}

Explained in detail here: typeofnan.blogspot.com/2011/04/did-you-know-episode-ii.html


Test against -1:

$.inArray('a', arr) !== -1

The above expression will return true/false.

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.

Source: http://api.jquery.com/jQuery.inArray/


Yep, compare to -1.

if ($.inArray('a', thearray) === -1) {
    // not found
}

You could wrap that into another function if it really bugs you:

function myInArray(needle, haystack) {
    return $.inArray(needle, haystack) !== -1;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜