![](/img/trans.png)
[英]Looping through an object and adding values to a Javascript object with the incremental count as the key
[英]javascript manipulate an object by adding/looping keys and values
我正在從事購物車功能練習。 該功能需要在cart
添加一件item
,並且它會打印出已添加到購物車中的item name
,或者如果未添加任何商品,則您的購物車為空。
我還需要創建一個對象來存儲Math.Random * 100生成的物料價格。
物品名稱和價格都應存儲在對象中。 該對象將傳遞給下一個函數,供用戶查看購物車。
這是我的嘗試,但它一次使多個項目保持不變。
function addToCart(item) {
item = ["pizza", "salt", "apples"]
var price = []
var priceRandom = Math.random() * 100
var priceItem = Math.floor(priceRandom)
for (var i =0; i<item.length; i++){
cart.push(item[i])
console.log(`${item[i]}has been added to your cart. `)
}
var cartList = {
item[i], priceItem[i]
}
return cartList
}
我不會做你的整個運動,我也不應該。
但是這里有一個對象“ items”,其中包含兩個數組(名稱和價格)
var items = {
names: ["pizza", "salt", "apples"],
price: []
}
使用forEach()
我們將遍歷items
對象中的所有names
,並為其指定價格。
items.names.forEach(function() {
var priceRandom = Math.random() * 100
var priceItem = Math.floor(priceRandom)
items.price.push(priceItem);
});
我想這就是你想要的
function shopingcart(items){ let cart =[]; items.forEach((v,i)=> {cart[i] = {food: v,price: Math.floor(Math.random(i)*100)}}); return cart } var items = ['pizza', 'salt', 'apples'] var cart = shopingcart(items); console.log(cart); // iterate by key value cart.forEach((item)=>{ console.log( item.price) console.log(item.food) })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.