【问题标题】:How to loop through javascript array of list and check if value exist then update else add new data如何遍历列表的javascript数组并检查值是否存在然后更新否则添加新数据
【发布时间】:2020-05-11 21:33:00
【问题描述】:

Determine whether an array contains a value 和 How do I check if an array includes a value in JavaScript? 已经回答了类似的问题,但似乎都没有解决我的问题。

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

// 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 incrementing 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 incrementing 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)

现在,当我再次单击 Cucumber 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


    【解决方案1】:

    您在每次迭代中立即执行 else,这是错误的

    它的作用是检查并匹配第一个元素中的值,如果匹配则更新,否则在购物车中添加新商品

    这发生在第二次迭代之前

    你应该做的是只检查是否在循环内并为它维护一个标志

    如果标志在循环存在之前未被触及,则表示该项目根本不在数组中

    在这里您可以添加新商品到购物车

    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 incrementing 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)
    }
    

    【讨论】:

      【解决方案2】:

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

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

      如果你应该支持 IE,那么使用 Map 的缺点就来了。否则使用 JavaScript 对象。

      如果您只想支持 IE11 和更高版本,请查看 JavaScript Map。

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

      1. 移除物品更容易、更干净
      2. 无需循环
      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 视图.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})
      

      【讨论】:

      • @EstebanBorai,我已在您的答案中添加了一些代码,您可以查看并恢复吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 2017-04-27
      • 1970-01-01
      相关资源
      最近更新 更多