javascript变量值是否随机显示?
我遇到了一个奇怪的问题。我正在建立一个在线商店,并展示了我的产品:javascript变量值是否随机显示?,javascript,innerhtml,Javascript,Innerhtml,我遇到了一个奇怪的问题。我正在建立一个在线商店,并展示了我的产品: var products = { 'Box1':{ 'price' : 10, 'quantity' : 10 }, 'Box2':{ 'price': 15, 'quantity' : 10 }, 'Clothes1':{ 'price': 20, 'quantity' : 10 }, 'Clothes2':{ 'price': 30, 'quantity' :
var products = {
'Box1':{
'price' : 10,
'quantity' : 10
},
'Box2':{
'price': 15,
'quantity' : 10
},
'Clothes1':{
'price': 20,
'quantity' : 10
},
'Clothes2':{
'price': 30,
'quantity' : 10
},
'Jeans':{
'price': 50,
'quantity' : 10
},
'Keyboard':{
'price': 20,
'quantity' : 10
},
'KeyboardCombo':{
'price': 40,
'quantity' : 10
},
'Box2':{
'Mice': 20,
'quantity' : 10
},
'PC1':{
'price': 350,
'quantity' : 10
},
'PC2':{
'price': 400,
'quantity' : 10
},
'PC3':{
'price': 300,
'quantity' : 10
},
'Tent':{
'price': 100,
'quantity' : 10
},
};
我还声明了一个全局变量
var priceTotal = 0;
我有一个addtocart函数,当我单击产品上的“添加”按钮时会调用它。这是工作的预期。我的函数如下所示:
function addToCart(productName) {
//var total = 5;
cart[productName]++;
products[productName].quantity --;
priceTotal = priceTotal + products[productName].price;
var element = document.getElementById("cartTotal");
element.innerHTML = "CartTotal($"+priceTotal+")";
}
无论出于什么原因,除了我添加Box2外,一切都按照我的要求运行。每当我单击add for box2时,我的priceTotal都会显示NaN,而不管priceTotal之前的值是多少。我曾尝试将price的值更改为不同的数字,但这种情况仍然存在。有人知道为什么会这样吗?这里是否有明显的错误,或者我是否需要显示更多的代码
谢谢如果您仔细查看,您无意中添加了两次框2,第二次是“鼠标”而不是“价格”,因此价格总值将被关闭 这意味着
priceTotal
或products[productName]。price
正在返回NaN
。。。添加控制台日志以查看哪个将成为NaN
-在priceTotal=priceTotal+products[productName]之前添加console.log('addToCart',productName,priceTotal,products[productName].price)
您的产品列表中有两次(第8次)出现在Box2框中,第二次没有价格,只有一个michatAnonymous0day。不知道我是怎么错过的欢迎你!我很高兴帮助你!