简体   繁体   English

javascript通过添加/循环键和值来操纵对象

[英]javascript manipulate an object by adding/looping keys and values

I am working on a shopping cart function exercise. 我正在从事购物车功能练习。 The function needs to take add one item in the cart , and it prints out item name has been added to your cart, or Your cart is empty if no item has been added. 该功能需要在cart添加一件item ,并且它会打印出已添加到购物车中的item name ,或者如果未添加任何商品,则您的购物车为空。

I also need to create an object to store the item prices generated by Math.Random * 100. 我还需要创建一个对象来存储Math.Random * 100生成的物料价格。

Both the item name and the item price should be stored in an object. 物品名称和价格都应存储在对象中。 The object will be passed on to the next function for user to view the cart. 该对象将传递给下一个函数,供用户查看购物车。

Here is my attempt, but it keeps turning more than one item at once. 这是我的尝试,但它一次使多个项目保持不变。

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

}

Im not going to do your whole exercise, neither should I. 我不会做你的整个运动,我也不应该。

But here you have an object ´items` which contains two arrays (name and price) 但是这里有一个对象“ items”,其中包含两个数组(名称和价格)

var items = {
    names: ["pizza", "salt", "apples"],
    price: []

}

And with a forEach() we will loop through all the names in the items object and give them a price. 使用forEach()我们将遍历items对象中的所有names ,并为其指定价格。

items.names.forEach(function() {
    var priceRandom = Math.random() * 100
    var priceItem = Math.floor(priceRandom)
    items.price.push(priceItem);
});

I think this is what you want 我想这就是你想要的

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM