如何解决$.inArray 不知道 item 是否在数组中
上下文
我有一个数组,其中包含网页上几个元素的索引。另一个数组包含元素可能具有的所有可能索引。我想遍历可能的索引数组,并根据页面上存在的索引检查每个值,以查看页面上是否有任何可能位于页面上的索引。我以这种方式在页面上找到索引:
var indices = $(".inputValue").map(function() {
return $(this).attr("value");
}).get();
当我console.log(indices)
:
["0","2","3"]
我要检查的可能索引数组如下:
var potentialIndices = [0,1,2,3];
然后我想获取 potentialIndices
内的每个值并将其与 indices
进行比较。在这种情况下,potentialIndices
包含数字 1,而 indices
不包含。
问题
我想表明数字 1 在 potentialIndices
而不是 indices
。我决定使用 $.inArray
和 forEach
循环来遍历 potentialIndices
数组中的每个项目。这是我使用的代码:
potentialIndices.forEach(function(item,index) {
if ($.inArray(potentialIndices,indices) > -1) {
console.log("in array");
} else {
console.log("not in array");
}
});
当我运行此代码时,我在控制台中得到 not in array
4 次。结果应该是“not in array”记录 1 次和“in array”记录 3 次。代码有问题吗?
我尝试过的事情
我已经尝试制作 potentialIndices
字符串而不是整数 (["0","1","3"]
),这并没有改变结果。
我还使用了 for
循环来尝试获得不同的结果:
for (var i = 0; i < potentialIndices.length; i++) {
if ($.inArray(potentialIndices[i],indices) > -1) {
console.log("in array");
} else {
console.log("not in array");
}
}
但我得到了相同的结果。
解决方法
您也可以使用 .filter
进行测试,或者实际上,只需使用 .forEach()
:
const tarr=["0","2","3"],parr = [0,1,2,3];
parr.filter(v=>tarr.indexOf(""+v)<0 && console.log(v+" is not in tarr."));
parr.forEach(v=>tarr.indexOf(""+v)<0 && console.log(v+" is not in tarr."));
为了在 parr
中找到 tarr
的元素,需要先将其与空字符串 (""+v
) 连接起来,将其转换为字符串。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。