Javascript 对照另一个数组检查数组项
我试图在数组中测试一个值,并根据该结果采取相应的行动,即,如果被测试的数组中不存在该项,则将其添加到数组中。我已经在这上面花了太多时间了,我真的需要一些帮助Javascript 对照另一个数组检查数组项,javascript,arrays,testing,Javascript,Arrays,Testing,我试图在数组中测试一个值,并根据该结果采取相应的行动,即,如果被测试的数组中不存在该项,则将其添加到数组中。我已经在这上面花了太多时间了,我真的需要一些帮助 function FilterItems(attrName, attrValue, priceMin, priceMax) { // check if item exists in filtered items for (var i = 0; i < adlet.item.length; i++
function FilterItems(attrName, attrValue, priceMin, priceMax) {
// check if item exists in filtered items
for (var i = 0; i < adlet.item.length; i++) {
if (adlet.item[i][attrName] == attrValue) {
var currentItem = adlet.item[i];
if (filteredItems.length > 0) {
// console.log(filteredItems.length);
for (var x = 0; x < filteredItems.length; x++) {
if (filteredItems[x].OMSID == currentItem.OMSID) {
// match found
break;
} else {
// match not found, add to filtered items.
filteredItems.push(currentItem);
}
}
} else {
filteredItems.push(adlet.item[i]);
// console.log(filteredItems.length);
}
}
}
函数过滤器项(attrName、attrValue、priceMin、priceMax){
//检查筛选项目中是否存在项目
对于(var i=0;i0){
//console.log(filteredItems.length);
对于(var x=0;x
您正在每个迭代中添加未找到的currentItem
。
filteredItems.push(currentItem);
如果未找到,则必须在循环后调用:
...
var found = false; // new 'found' var = true if currentItem is found
for (var x = 0; x < filteredItems.length; x++) {
if (filteredItems[x].OMSID == currentItem.OMSID) {
// match found
found = true;
break;
}
}
// match not found, add to filtered items.
if (!found) {
filteredItems.push(currentItem);
}
} else {
filteredItems.push(adlet.item[i]);
// console.log(filteredItems.length);
}
...
。。。
var found=false;//如果找到currentItem,则新的“found”var=true
对于(变量x=0;x
/*
如果对数组执行任何操作,那么数组方法“indexOf”非常有用,不能忽略。这里有一个基于Mozilla代码的垫片
此处显示的方法“add”的工作原理类似于push,但它仅在项目不在数组中时添加项目。可以添加具有多个参数的多个项
“merge”将把调用数组中的所有“new”项添加到作为参数发送的数组中,
*/
if(!Array.prototype.indexOf){
Array.prototype.indexOf=函数(what,i){
i=i | | 0;
var L=此长度;
而(i 虽然(i这里是函数的简化版本,它仅在内部循环完成后添加过滤器项:
function FilterItems(attrName, attrValue, priceMin, priceMax) {
for (var i = 0; i < adlet.item.length; i++) {
if (adlet.item[i][attrName] == attrValue) {
var currentItem = adlet.item[i];
var found = false;
for (var x = 0; x < filteredItems.length; x++) {
if (filteredItems[x].OMSID == currentItem.OMSID) {
found = true;
break;
}
}
if (!found)
filteredItems.push(currentItem);
}
}
}
函数过滤器项(attrName、attrValue、priceMin、priceMax){
对于(变量i=0;i
什么是filteredItems
以及它是如何定义的?什么是adlet
以及它是如何定义的?有趣的是,我只是在写相同的代码…即使使用相同的变量名。:)
function FilterItems(attrName, attrValue, priceMin, priceMax) {
for (var i = 0; i < adlet.item.length; i++) {
if (adlet.item[i][attrName] == attrValue) {
var currentItem = adlet.item[i];
var found = false;
for (var x = 0; x < filteredItems.length; x++) {
if (filteredItems[x].OMSID == currentItem.OMSID) {
found = true;
break;
}
}
if (!found)
filteredItems.push(currentItem);
}
}
}