function创建对象并将其推送到数组

时间:2017-01-26 10:33:38

标签: javascript arrays object

我希望我的函数创建一个对象,然后将其推送到一个数组, 我的代码问题是它是推送元素,因为它只是一个数组而不是对象,当我控制台日志它应该显示它像[{name:" blabla",price:25},{name: " blabla2",价格:10}]。这是我的代码:



var shoppingCart = [];
function addToCart (itemName,itemPrice) {
  this.name = itemName;
  this.price = itemPrice;
  return shoppingCart.push(itemName,itemPrice)
}
addToCart ("baba",25);
addToCart ("choco",85);
console.log(shoppingCart);




4 个答案:

答案 0 :(得分:2)

像这样?

var shoppingCart = [];
function addToCart (itemName,itemPrice) {
  shoppingCart.push({name: itemName, price: itemPrice});
}
addToCart ("baba",25);
addToCart ("choco",85);
console.log(shoppingCart);

答案 1 :(得分:0)

您是否考虑过使用这样的shoppingCart对象?

var shoppingCart = {
	items: [],
	getItems: function(){
		return this.items;
	},
	add: function(itemName,itemPrice) {
			var newItem = {name: itemName, price: itemPrice};
			this.items.push(newItem);
		}
}

shoppingCart.add("baba",25);
shoppingCart.add("choco",85);

console.log(shoppingCart.getItems());

答案 2 :(得分:0)

var shoppingCart = [];
function addToCart (itemName,itemPrice) {
  this.name = itemName;
  this.price = itemPrice;
  return shoppingCart.push({name: itemName, price: itemPrice});
}
addToCart ("baba",25);
addToCart ("choco",85);
console.log(shoppingCart);

function priceCheck (itemStore) {
  for (var i=0;i<shoppingCart.length;i++) {
    if (shoppingCart[i].name = itemStore) {
      console.log("The price is " + this.price + " shekels" );
    }
    else {
      console.log("that item is not in your cart");
    }
  }
}
priceCheck ("baba");
console.log(shoppingCart);

function totalPriceCheck () {
  var total = 0;
  for (var i=0;i<shoppingCart.length;i++) {
    total += shoppingCart[i].price;
  }
  return total;
}
totalPriceCheck();

正如你所看到的第一个问题是priceCheck,由于某些原因,当我登录日志时,它给了我两次巴巴名字并认为巴巴是85而不是25

第二个问题是totalPriceCheck谁给我一个NaN,我应该从我的数组对象中得到价格属性的总和

答案 3 :(得分:0)

RE:你上面的帖子,这解决了它

var shoppingCart = [];
function addToCart (itemName,itemPrice) {
  this.name = itemName;
  this.price = itemPrice;
  return shoppingCart.push({name: itemName, price: itemPrice});
}
addToCart ("baba",25);
addToCart ("choco",85);
console.log(shoppingCart);

function priceCheck (itemStore) {
  for (var i=0;i<shoppingCart.length;i++) {
    if (shoppingCart[i].name = itemStore) {
      console.log("The price is " + shoppingCart[i].price + " shekels" );
      break;
    }
    else {
      console.log("that item is not in your cart");
    }
  }
}
priceCheck ("baba");
console.log(shoppingCart);

function totalPriceCheck () {
  var total = 0;
  for (var i=0;i<shoppingCart.length;i++) {
    total += shoppingCart[i].price;
  }
  return total;
}
console.log(totalPriceCheck());