开发者

jQuery inArray - problems

Say I have a variable a with the value:

1

Then I have an array b with the values:

开发者_StackOverflow中文版
[1, 2]

Why does $.inArray(a, b) give me a -1? I should be getting 0, right?


Exactly what you described gives me 0[fiddle]:

var a = 1, b = [1, 2];
alert($.inArray(a, b)); // alerts "0"

However, I can replicate your results when I do this (as suggested by IAbstractDownvoteFactory):

var a = 1, b = ["1", "2"];
alert($.inArray(a, b)); // alerts "-1"
var a = "1", b = [1, 2];
alert($.inArray(a, b)); // alerts "-1"

.inArray only finds matches that are the same type as what you're searching with (they're compared with ===). If you can't make your input data the right format, you can do it yourself:

To convert a to a number:

a = +a; // or a = Number(a);

To convert all elements of b to numbers:

for (var i = 0; i < b.length; i++) {
    b[i] = +b[i];
}


Rather than convert to numbers it may be better to convert to strings, such as in an instance where you are usings ids for say a plot where in some case they will numeric entity id and in others case a string, e.g. country code for United Kingdom is GB.

Ensure all values are set as strings

Arr[] = mixedValue.toString();

And then always ensure your comparison needle is a string

if ($.inArray(needle.toString(), Arr) === -1) {
    // nope
} else {
    // yep
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜