gpt4 book ai didi

jquery - jQuery .inArray() 的工作原理

转载 作者:行者123 更新时间:2023-12-01 06:44:58 26 4
gpt4 key购买 nike

简短的查询是,在下面的代码中为什么它不打印找到?

var products = [];
products.push("ABC", "XYZ");
var compareProducts = ["ABC","XYZ"];

console.log(products)


if($.inArray(products, compareProducts) > -1)
{
alert("found");
}
else{
alert("not found");
}

最佳答案

根据文档,

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

这就是它的工作原理:

inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
}

它会查找 elemarr 中的出现情况。它没有发现一个数组的对象在另一个数组中出现。

如果您想检查 products 中的所有项目是否存在于 compareProducts 中,您可以迭代该数组或使用 Array.prototype.every:

var products = [];
products.push("ABC", "XYZ");

var compareProducts = ["ABC","XYZ"];

if (products.every(function(x) { return $.inArray(x, compareProducts) > -1; }))
{
alert("found");
} else {
alert("not found");
}

关于jquery - jQuery .inArray() 的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34127650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com