简体   繁体   English

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

[英]How to loop through javascript array of list and check if value exist then update else add new data

Similar questions have been answered here Determine whether an array contains a value and here How do I check if an array includes a value in JavaScript?类似的问题已在此处回答确定数组是否包含值和此处如何检查数组是否包含 JavaScript 中的值? , but none of them seems to solve my problem. ,但它们似乎都不能解决我的问题。

The comments in my code explain the details of what I want to achieve.我的代码中的注释解释了我想要实现的细节。

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

Here are the console logs:以下是控制台日志:

First time click:第一次点击:

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

Second time click on the same product:第二次点击同一产品:

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)

First time click on a different product to have two different list of items in list:第一次单击不同的产品以在列表中有两个不同的项目列表:


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)

Now when I click on Cucumber Poinsett / kg again, instead of updating the quantity it add it again.现在,当我再次单击 Cucumber Poinsett / kg 时,它不再更新数量,而是再次添加它。

That is where I don't know where the error is coming from:那是我不知道错误来自哪里的地方:

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
``

You are instantly doing else inside each iteration, which is wrong您在每次迭代中立即执行其他操作,这是错误的

What this does is, it check & matches value in first element, if matches then it does update else it adds new item in cart它的作用是,它检查并匹配第一个元素中的值,如果匹配则它会更新,否则它会在购物车中添加新项目

This happens before going to second iteration这发生在进行第二次迭代之前

what you should do is check only if inside loop & maintain a flag for it您应该做的是仅检查是否在内部循环并为其维护标志

If the flag is untouched till the loop exists, means the item is not in the array at all如果该标志在循环存在之前未受影响,则表示该项目根本不在数组中

Here you can add new item in cart在这里您可以在购物车中添加新项目

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

How I see this, I think your first issue comes from the kind of implementation.我怎么看,我认为你的第一个问题来自于实现的类型。 The code is intuitive but the problem is that is also complex and leaks performance.代码很直观,但问题是它也很复杂并且会泄漏性能。

A better implementation could be achieved using another data structure such as a Map (Hash Map/Hash Table).使用另一种数据结构(例如 Map(哈希映射/哈希表))可以实现更好的实现。

The downside of using Map comes if you should support IE or not.如果您是否应该支持 IE,则使用 Map 的缺点就来了。 Otherwise use a JavaScript Object.否则使用 JavaScript 对象。

Please checkout JavaScript Map if you only want support for IE11 and newer.如果您只想支持 IE11 及更新版本,请查看JavaScript Map

Otherwise using a key/value data structure is a great idea:否则使用键/值数据结构是一个好主意:

  1. Removing items is easier and cleaner移除物品更容易、更清洁
  2. No loops needed不需要循环
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);

At this point, as Im using the same reference for cart, I think you could implement a Cart prototype, but for a quick sample of what I think is a better approach that's it!在这一点上,由于我对购物车使用了相同的参考,我认为您可以实现购物车原型,但是对于我认为更好的方法的快速示例,就是这样!

Hope it helps!希望能帮助到你!

my html code我的 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 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})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查JavaScript数组中是否存在某个值,继续添加0.15直到它不存在,然后将该值添加到数组的末尾? - How to check if a value exists in a JavaScript array, continue to add 0.15 until it does not exist, then add that value to the end of the array? 如何检查json数组中是否存在值javascript - How to check if value exist in a json array javascript Javascript 检查二维数组更新中是否存在值,否则创建 - Javascript check if value exists in 2d array update else create 如何检查数组并在JavaScript中添加新的Cookie - How to check array and add new cookie in javascript 如何基于其他数组遍历数组中的每个值并使用 javascript 检查它是否符合某些条件? - How to loop through each value in array based on other array and check if it matches some condition using javascript? 循环遍历 javascript 数组,将值添加到另一个数组 - loop through a javascript array add the value to another array 如何遍历对象数组并使用 react 和 javascript 添加新字段? - How to loop through an array of objects and add a new field using react and javascript? 如何遍历对象数组并根据 JavaScript 中的条件添加新的对象键? - How to loop through array of objects and add new object key based on condition in JavaScript? JavaScript自动售货机检查项目是否存在否则新的和库存变化 - JavaScript Vending Machine Check if Item exist else new and stock change 如何通过for循环将新数据添加到数组 - How to add new data to array by for loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM