我正在为一个类项目编写一些代码,并且遇到了以下代码的问题:
var sellEverything = function(gold)
{
console.log("You decide to buy EVERYTHING.");
var holder;
while (storeStock.length > 0)
{
console.log(storeStock);
var curItem = storeStock.pop();
console.log(curItem);
console.log("You buy a " + curItem.itemName + " for " + curItem.itemPrice + " gold.");
gold -= curItem.itemPrice;
console.log(gold + " gold remaining");
};
};
从角度来看,storeStock 是一个包含 6 个对象的数组。curItem 变量在控制台中显示为未定义,因此甚至可以从数组中弹出对象还是问题出在什么地方?
以下是 storeStock 填充的数据:
"items":
[
{"itemName":"Sword", "itemPrice":100},
{"itemName":"Bow", "itemPrice":240},
{"itemName":"Shield", "itemPrice":120},
{"itemName":"Lance", "itemPrice":300},
{"itemName":"Potion", "itemPrice":50},
{"itemName":"Gem of supreme power", "itemPrice":5},
{"itemName":"Better movie script", "itemPrice":139083882}
]
如果这是一个明显的问题,请提前道歉。
编辑:好的,为了清楚起见,我觉得我需要显示整个代码:
var itemList =
{
"items":
[
{"itemName":"Sword", "itemPrice":100},
{"itemName":"Bow", "itemPrice":240},
{"itemName":"Shield", "itemPrice":120},
{"itemName":"Lance", "itemPrice":300},
{"itemName":"Potion", "itemPrice":50},
{"itemName":"Gem of supreme power", "itemPrice":5},
{"itemName":"Better movie script", "itemPrice":139083882}
]
};
//private class ItemStore
var ItemStore = function()
{
var storeStock = [];
//array in function
var setStockList = function(stockArray)
{
if (stockArray instanceof Array)
{
var i = stockArray.length;
for (i; i > 0; i--)
{
storeStock.push(stockArray[i]);
}
//yes, I could have just done the loop forwards, but wanted to do it this way.
storeStock.reverse();
};
};
//array out function
var getStockList = function()
{
return (storeStock);
};
var sellEverything = function(gold)
{
console.log("You decide to buy EVERYTHING.");
var holder;
while (storeStock.length > 0)
{
console.log(storeStock);
var curItem = storeStock.pop();
console.log(curItem);
console.log("You buy a " + curItem.itemName + " for " + curItem.itemPrice + " gold.");
gold -= curItem.itemPrice;
console.log(gold + " gold remaining");
};
};
return{
"setStockList": setStockList,
"sellEverything": sellEverything,
"getStockList":getStockList
};
};
另外值得注意的是我如何调用 setStockList 方法:
store.setStockList(itemList.items);