我无法弄清楚为什么当lastProductID在数组中时,我为lastProductIndex持续获得-1!
var lastProductID = 6758;
var allProductIDs = [5410, 8362, 6638, 6758, 7795, 5775, 1004, 1008, 1013]
var lastProductIndex = $.inArray(lastProductID, allProductIDs);
Run Code Online (Sandbox Code Playgroud)
Age*_*nce 44
我昨天遇到了同样的问题,
var data=[2,4,6,8];
alert( $.inArray(4,data) ) // output 1 as expected
alert( $.inArray("4",data) ) // output -1 as expected
Run Code Online (Sandbox Code Playgroud)
通常,当您从输入元素或返回字符串的内容中获取要检查的值时,会发生这种情况.您需要parseInt(string,radix)将其转换为数字...
试试这个:
$.grep(allProductIDs, function(n) { return n == lastProductID; });
Run Code Online (Sandbox Code Playgroud)
警告:grep返回一个数组.
看起来jQuery用inArray做了===而不是==.
这就是为什么每个人都讨厌非TYPED的语言.我最初使用一个值设置lastProductIndex值,但它是一个字符串(因为我从返回的JSON中获取了HttpResponse对象的值.因此我将变量设置为字符串,因为返回的JSON值是一个字符串当我将数字6758硬编码为$ .inArray时,它工作正常,引起了我的注意.
您的页面中是否使用了任何其他 JavaScript 库?
$如果是的话,可能会出现速记冲突。这可以通过多种方式解决,其中之一是将代码包装在自动执行的匿名函数中
(function($) {
var lastProductIndex = $.inArray(lastProductID, allProductIDs);
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34380 次 |
| 最近记录: |