Javascript 从数组中删除项不起作用

Javascript 从数组中删除项不起作用,javascript,arrays,Javascript,Arrays,我有一个名为cartarray的数组,格式如下 1: {id: "1510-01-312-3501-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514542566148", name: "AIRPLANE UTILITY", price: "$90", quantity: "1"} 2: {id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", pr

我有一个名为cartarray的数组,格式如下

1: {id: "1510-01-312-3501-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514542566148", name: "AIRPLANE UTILITY", price: "$90", quantity: "1"}

2: {id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "$43", quantity: "3"}

3: {id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "$43", quantity: "1"}
下面的html由上面的数组填充

cartarry.products.forEach(function(element) {
    var id = element.id;
    var itemname = element.name;
    var itemprice = element.price;
    var itemcard = `
              <div class="product" id="${id}">
                        <div class="product-image">
                          <img src="https://s.cdpn.io/3/dingo-dog-bones.jpg">
                        </div>
                        <div class="product-details">
                          <div class="product-title">Dingo Dog Bones</div>
                          <p class="product-description"> ${itemname}</p>
                        </div>
                        <div class="product-price">${itemprice}</div>
                        <div class="product-quantity">
                          <input type="number" value="2" min="1">
                        </div>
                        <div class="product-removal">
                          <button class="remove-product">
                            Remove
                          </button>
                        </div>
                <div class="product-line-price">25.98</div>
                </div>

            `;
    itemcontainer.innerHTML += itemcard;
})       
不管我点击了哪个项目,我都会得到-1作为索引,这会阻止该项目被删除。如何修复此问题并从阵列中删除单击的项

在数组中找不到它,因为这是一个DOM元素

您可以使用搜索包含id的项目的索引


在原始代码中,单击的是DOM元素,而不是实际的产品。上述代码从单击的元素中获取id,并仅获取没有单击id的cartarry产品。

首先,您从cartarry.products创建了一个item对象,您将无法从cartarry.products中删除该元素,因为您正在从item中删除它,您可以使用以下代码按特定属性查找元素:

  var index = cartarry.products.map(function(element) {
          return element.id;
        }).indexOf(this.id);
我为您创建了一个plunkr示例:

var findId = this.id;

var match = items.findIndex(function (el) {
  return el.id == findId;
});

if (match > -1) {
  items.splice(match, 1);
}
$('.product').on(
    'click',
    ({ id }) => cartarry.products = carrtarry.products.filter(pr => pr.id != id)
)
  var index = cartarry.products.map(function(element) {
          return element.id;
        }).indexOf(this.id);