如何遍历列表的javascript数组并检查值是否存在,然后更新否则添加新数据

问题描述 投票:1回答:2

这里Determine whether an array contains a value和这里How do I check if an array includes a value in JavaScript?都回答了类似的问题,但是似乎没有一个问题可以解决我的问题。

我代码中的注释解释了我想要实现的细节。

// I have an empty array that i will add items to it using onclick function
var list = []
//Now here is my add to cart function
function addToCart(productName, productPrice, url, description, quantity) {
//First check if the list is empty, then no need to loop through you just add the item to cart
if (list.length === 0) {
list.push({ name: productName, price: productPrice, url: url, quantity: 1 });
 console.log(list)
 console.log('adding first item')
 //if not empty then loop through
} else {
for (var i = 0; i < list.length; i++) {
//if the product name of the item clicked in already in the array 
//then no need to add but get the quantity and increment it by 1
   if (list[i].name === productName) {
list[i].quantity++
console.log('same product not adding, we are increamenting the quantity by 1 ')
console.log(list)
} else {
 // if the name of product clicked  does not exist then add it to the list
 // here is where there problem comes, when there is only one product in the list 
 // everything works fine, but when there are two different kinds of products in the list 
 //  as shown in a console log below, then you click on
 // one of these items it increment the quantity then add the same item again
 list.push({ name: productName, price: productPrice, url: url, quantity: 1 });
 console.log('does not exist, am adding now')
console.log(list)
}
}
    }
}

这是控制台日志

第一次点击

[{ … }]
0: { name: "Bell pepper", price: "3", url: "https://firebasestora…=media&tokenc", quantity: 1 }
length: 1
__proto__: Array(0)

第二次单击相同的产品

same product not adding, we are increamenting the quantity by 1
[{ … }]
0:
name: "Bell pepper"
price: "3"
url: "https://firebasestorage.googleapis.com/v0/b/ps-farms.appspoc"
quantity: 2
__proto__: Object
length: 1
__proto__: Array(0)

第一次单击其他产品,在列表中有两个不同的项目列表


does not exist, am adding now
 (2)[{ … }, { … }]
0: { name: "Bell pepper", price: "3", url: "https://firebasestoc", quantity: 2 }
1: { name: "Cucumber Poinsett/kg", price: "7.5", url: "https://firebasest", quantity: 1 }
length: 2
__proto__: Array(0)

现在当我再次单击黄瓜Poinsett / kg时,无需更新数量,而是再次添加它

那是我不知道错误来自何处

does not exist, am adding now
(3)[{ … }, { … }, { … }]
0: { name: "Bell pepper", price: "3", url: "https://firebasesto/4858c", quantity: 2 }
1: { name: "Cucumber Poinsett / kg", price: "7.5", url: "https://firebasestorage.c74c", quantity: 1 }
2: { name: "Cucumber Poinsett / kg", price: "7.5", url: "https://firebasest74c", quantity: 1 }
length: 3

``
javascript arrays algorithm for-loop javascript-objects
2个回答
2
投票

您在每个迭代中立即执行其他操作,这是错误的

这是什么,它检查并匹配第一个元素中的值,如果匹配则更新并在购物车中添加新项目

此操作发生在第二次迭代之前

您应该做的是仅检查内部循环并为其维护一个标志

如果在循环存在之前未触摸该标志,则意味着该项目根本不在数组中

这里您可以在购物车中添加新项目

var exist = false;
for (var i = 0; i < list.length; i++) {
    //if the product name of the item clicked in already in the array 
    //then no need to add but get the quantity and increment it by 1
    if (list[i].name === productName) {
        list[i].quantity++;
        console.log('same product not adding, we are increamenting the quantity by 1 ');
        console.log(list);
        exist = true;
    }
}

if(!exist){
    // IF  EXIST is still false, the item is definately nowhere inside the array

    // if the name of product clicked  does not exist then add it to the list
    // here is where there problem comes, when there is only one product in the list 
    // everything works fine, but when there are two different kinds of products in the list 
    //  as shown in a console log below, then you click on
    // one of these items it increment the quantity then add the same item again
    list.push({ name: productName, price: productPrice, url: url, quantity: 1 });
    console.log('does not exist, am adding now')
    console.log(list)
}

0
投票

我如何看待这个问题,我认为您的第一个问题来自实施的方式。该代码很直观,但是问题在于它也很复杂并且会泄漏性能。

可以使用另一个数据结构,例如Map(哈希映射/哈希表)来实现更好的实现。

如果您不应该支持IE,则使用Map的缺点是。否则,请使用JavaScript对象。

如果仅希望支持IE11和更高版本,请结帐JavaScript Map。>>

否则使用键/值数据结构是一个好主意:

  1. 删除项目更容易,更清洁
  2. 不需要循环
  3. const cart = {};
    
    // handle click
    function handleClick(product) {
      if (product.id in cart) {
        // Updates quantity by one
        cart[product.id] = {...cart[product.id],
          // Update values for this product in the cart
          quantity: cart[product.id] + 1
        }
      } else {
        Add product to cart object
        cart[product.id] = product;
      }
    }
    
    // Turn into array if necessary
    Object.values(cart);
    

在这一点上,因为我对购物车使用相同的参考,所以我认为您可以实现购物车原型,但是快速了解一下我认为是更好的方法!

希望有帮助!

我的HTML代码

{% block content %}
   {% for doc in product %}
<div class="jumbotron">
<div class="col-sm-4">
<div class="card" >
 <div class="card-body">
<a href="#" class="img-prod"><img class="img-fluid" id="productUrl" src="{{doc.productImage}}"  alt="{{doc.productName}}">
 <h1 class="card-title" id="productName">{{doc.name}}</h1>
 <p class="card-subtitle mb-2 text-muted" id="productPrice">{{doc.price}}</p>
 <p class="card-text" id="productDescription">{{doc.description}}</p>
<button type="button" onclick="addToCart('{{doc.productName}}','{{doc.price}}','{{doc.productImage}}','{{doc.description}}')">Add to cart</button>
 </div>
 </div>
</div>
</div>
{% endfor %}
{% endblock content %} 

Django view.py

def home(request):
    collection_ref = db.collection(u'products').get()
    documents = list(doc.to_dict() for doc in collection_ref)
    return render (request,'store/home.html',{'product':documents})
© www.soinside.com 2019 - 2024. All rights reserved.