【发布时间】:2017-02-26 23:19:49
【问题描述】:
我无法显示随机对象和该随机对象的属性。这个项目的目标是有一个 stockItems 列表,当我按下一个按钮时,它会选择一定数量的这些对象并将它们显示在 HTML p 标记中。现在,当我尝试显示它时,它会打印为 [object]。目标是使所选对象的属性位于不同的行上。
这是我正在使用的代码:
function buildShopItems(count) {
var shopItems = [], i, itemIndex;
count = stockItems.length < count ? stockItems.length : count;
function getUniqueRandomItem() { //from stock
var item;
while (true) {
item = stockItems[Math.floor(Math.random() * stockItems.length)];
if (shopItems.indexOf(item) < 0) return item;
}
}
for (i = 0; i < count; i++) {
shopItems.push(getUniqueRandomItem());
}
return shopItems;
console.log(shopItems);
}
var stockItems = [
{ item: "sword", type: "weapon", weight: "5 lbs.", cost: "10 gold" },
{ item: "hammer", type: "weapon", weight: "8 lbs.", cost: "7 gold" }
//...
];
var shopItems = buildShopItems(1);
console.log(shopItems);
document.getElementById("item").innerHTML = shopItems.item;
document.getElementById("type").innerHTML = shopItems.type;
document.getElementById("weight").innerHTML = shopItems.weight;
document.getElementById("cost").innerHTML = shopItems.cost;
【问题讨论】:
-
使用JSHint 立即查找代码问题。您应该已经看到了
unreachable code after return statement警告。 -
你的上层
console.log(shopItems);永远不会执行,因为你在它之前运行了一个return。另外,while(true){}从来没有是个好主意... -
shopItems是一个数组。shopItems.item之类的没有意义。 -
@Xufox 我将使用什么来显示该数组中随机选择的对象?
-
@ObsidianAge 除了while(true){},你有什么建议吗?
标签: javascript html arrays variables object