好吧,所以我一直在研究这个。我使用For循环比较两个数组的值。每次称为cart的数组都会命中一个可以在products数组中找到的数字,它会在每次命中时显示products数组的信息。我认为我的代码本身很好(虽然我可能错了)但它没有显示值。所以我认为我在那里执行所述流程有问题。代码如下
function Fill(){
var txt=""
var products = new Array();
products[0] = {name: "refrigerator" , price:88.99, img:"img/refrigerator.jpg"};
products[1] = {name: "microwave oven" , price: 76.99 , img:"img/microwave.jpg"};
products[2] = {name: "dishwasher" , price:276.67 , img:"img/dishwasher.jpg"};
var carts = new Array ();
carts[0]= 2;
carts[1]= 0;
carts[2]= 1;
carts[3]= 1;
carts[4]= 0;
carts[5]= 1;
carts[6]= 2;
carts[7]= 2;
for(var i=0; i < carts.length; i++){
for(var j = 0; j < products.length; j++){
if(carts[i] == j){
txt +=products[j].name + ' ' + products[j].price +" <img src='"+ products[j].img + "'>"
document.getElementById("answer").innerHTML += txt
}
}
}
}
答案 0 :(得分:3)
“carts”是一个数字数组(根据您的源代码),而“products”是一个对象数组。所以你的条件“carts [i] == products [j]”永远不会开火。
答案 1 :(得分:3)
const products=[{name:"refrigerator",price:88.99,img:"img/refrigerator.jpg"},{name:"microwave oven",price:76.99,img:"img/microwave.jpg"},{name:"dishwasher",price:276.67,img:"img/dishwasher.jpg"}];
const carts=[2,0,1,1,0,1,2,2];
const productsInCart = [...new Set(carts)]
.reduce((a,c)=>{
a.set(c,products[c])
return a;
}, new Map());
const res = carts.map(c=>{
const {name, price, img} = productsInCart.get(c)
return `${name} ${price} <img src="${img}"/>`;
}).join("");
document.body.innerHTML = res;
您应该将carts[i]
与j
进行比较,否则您将找不到任何内容
var txt = ""
var products = new Array();
products[0] = {
name: "refrigerator",
price: 88.99,
img: "img/refrigerator.jpg"
};
products[1] = {
name: "microwave oven",
price: 76.99,
img: "img/microwave.jpg"
};
products[2] = {
name: "dishwasher",
price: 276.67,
img: "img/dishwasher.jpg"
};
var carts = new Array();
carts[0] = 2;
carts[1] = 0;
carts[2] = 1;
carts[3] = 1;
carts[4] = 0;
carts[5] = 1;
carts[6] = 2;
carts[7] = 2;
for (var i = 0; i < carts.length; i++) {
for (var j = 0; j < products.length; j++) {
if (carts[i] == j) {
txt = products[j].name + ' ' + products[j].price + " <img src='" + products[j].img + "'>"
document.getElementById("answer").innerHTML += txt
}
}
}
<div id="answer"></div>
您的txt
变量应使用=
修改,而不是+=
您应优化代码。例如,document.getElementById("answer")
可以在全球范围内启动。
答案 2 :(得分:1)
您的设备变量的价值是多少? 它会导致代码出错。
还要窃取亚历克斯的回答:&#34;推车&#34;是一组数字(根据您的源代码),而#34;产品&#34;是一个对象数组。所以你的情况&#34;推车[i] ==产品[j]&#34;永远不会开火。
也许这样更好?
carts[7]= 2;
for(var i=0; i < carts.length; i++){
txt +=products[carts[i]].name + ' ' + products[carts[i]].price +" <img src='"+ products[carts[i]].img + "'>"
document.getElementById("answer").innerHTML += txt
}
&#13;
Upvoting Grimbode的答案,因为它非常接近我的,但更清洁。
答案 3 :(得分:0)
我不确定为什么你需要第二个for循环。您通过执行此操作来尝试将数字与产品对象进行比较,但它永远不会起作用。好吧,假设你想要实现的是如果购物车[0] = 2你想要产品的信息[2]那么尝试类似的东西:
for(i=0; i<carts.length; i++) {
if(i<products.length) {
currProd=products[carts[i]];
//Process the currProd object as you will
}
}