-1
我無法顯示隨機對象和該隨機對象的屬性。這個項目的目標是要有一個stockItems列表,當我按下一個按鈕時,它會選擇一個確定數量的這些對象,並將它們顯示在HTML標籤中。現在,當我嘗試顯示它時,它將打印出[對象]。目標是讓所選對象的屬性位於不同的行上。我無法顯示隨機選擇的對象
這裏是我一起工作的代碼:
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](http://jshint.com/)立即查找代碼問題。您應該已經在返回語句警告之後看到了'無法訪問的代碼。 – Xufox
您的上層'console.log(shopItems);'永遠不會執行,因爲您在它之前運行'return'。此外,'while(true){}'是**從來不是一個好主意...... –
'shopItems'是一個數組。 'shopItems.item'等沒有意義。 – Xufox