使用拼接进行数组操作

时间:2018-04-05 04:24:11

标签: javascript

我有这个数组两个函数,一个添加到它,另一个带走它或至少是计划。有人可以查看我的代码,看看我的第二个功能有什么问题。 splice将我的最后一个元素放在数组上,但不是我想要获取的特定元素。请

var shoppingCart = [];
function AddtoCart(name, description, price) {
  // JavaScript Object that  holds three properties :    Name,Description and Price
  var singleProduct = {};
  //Fill the product object with data
  singleProduct.Name = name;
  singleProduct.Description = description;
  singleProduct.Price = price;
  //Add newly created product to our shopping cart 
  shoppingCart.push(singleProduct);
  //call display function to show on screen

}

function removefromCart(name, description, price) {
  // JavaScript Object that will hold three properties :    Name,Description and Price
  var singleProduct = {};
  //Fill the product object with data
  singleProduct.Name = name;
  singleProduct.Description = description;
  singleProduct.Price = price;
  var index = shoppingCart.indexOf(singleProduct);
  shoppingCart.splice(index, 1);
}

1 个答案:

答案 0 :(得分:3)

removefromCart内,singleProduct是一个新创建的对象,所以它肯定不会存在于shoppingCart中,即使它具有相同的属性 - 非原型的变量(例如as objects)实际上指向内存位置,所以如果你创建一个新对象,指向该对象的变量有一个新的内存位置,脚本中没有其他内容可以知道,所以anyArr.indexOf(newObject)将始终返回-1。

改为使用.findIndex

function removefromCart(name, description, price) {
  const index = shoppingCart.findIndex(({ Name, Description, Price }) => (
    name === Name &&
    description === Description &&
    price === Price
  ));
  if (index === -1) {
    console.log('No matching product found!');
    return;
  }
  shoppingCart.splice(index, 1);
}
相关问题