如何在Node.js的while循环中正确使用for循环 [英] How to properly use a for loop inside of a while loop in nodejs

查看:55
本文介绍了如何在Node.js的while循环中正确使用for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理购物车应用程序.用户将其产品添加到使用本地存储来存储该信息的购物车.当用户访问查看购物车页面时,该页面需要提供所有产品的视图以及用户将该特定产品添加到购物车的次数.因此,我正在使用ajax请求将本地存储中的项目发送到后端.然后,我找到关联的信息,并在后端建立一个带有该数据的表,然后通过ajax将其发送到前端.

I am working on a shopping cart application. A user adds their products to the cart which is using local storage to store that information. When the user visits the view cart page, the page needs to give a view of all of the products and the number of times the user has added that specific product to the cart. So what I am doing is sending the items in local storage to the back end using an ajax request. I then find the affiliated information and build a table with that data on the back end and send it to the front end via ajax.

这里是控制器,它正在接收数据并构建表,然后将其发送回前端.

Here is the controller that is receiving the data and building the table, to then send it back to the front end.

viewCartPost: function(req, res){
      var data = JSON.parse(req.body.data);
      var keys = Object.keys(data);
      //console.log(keys);
      var promises = [];
      for(var i = 0; i<keys.length; i++){
        var productId = keys[i];
        promises.push(Product.find({productId: productId}).select({productId : 1, addProductGroupName: 1, productName: 1, productPrice: 1, productDescription: 1, filePath: 1}).exec());
      }
      Promise.all(promises).then(function(results) {
          // you may have to reorganize results to be exactly what you want
          // to return to the client
          var cartTable = viewCartTable(results, data);
          res.send("Success^^^"+cartTable);
      }).catch(function(err){
          res.sendStatus(500);
      });
    },

function viewCartTable(results, data){
  for(var i in data){
    console.log(data[i].count);
    var count = data[i].count;
  }
  var len = results.length;
  var i = 0;
  var table = '<table class="table-striped table-bordered" id="tables">';
  table += '<thead>';
  table += '<tr>';
  table += '<th>Image</th><th>Product Name</th><th>Price</th><th>Amount</th><th>Description</th><th>Update</th>';
  table += '</tr></thead><tbody>';

  while(i < len){
    table += '<tr>';
    table += '<td><img src='+results[i][0].filePath+' alt="An Image" class="thumbnail-img" /></td>';
    table += '<td id = "productName">'+results[i][0].productName+'</td>';
    table += '<td id = "'+results[i][0].productPrice+'">$'+results[i][0].productPrice+'</td>';
    table += '<td>'+count+'</td>';
    table += '<td><button type="button" id="productDescription" class="btn btn-primary" name = "'+results[i][0].productId+'">Description</button></td>';
    table += '<td><button type="button" class="btn btn-success" id="updateCartBtn" name = "'+results[i][0].productId+'">Update</button></td>';
    table += '</tr>';
    i++;
  }
  table += '</tbody></table>';
  return table;
}

一切正常.接受for(var i in data){}循环.这将获取已添加到本地存储中的对象字典的值.console.log(data)如下所示: {rJUg4uiGl:{productPrice:'78 .34',count:1},BJ_7VOiGg:{productPrice:'3000',count:3}}

Everything works out extremely well. Accept for the for(var i in data){} loop. This is getting the values of a dictionary of objects that have been added to the local storage. the console.log(data) looks like so: { rJUg4uiGl: { productPrice: '78.34', count: 1 }, BJ_7VOiGg: { productPrice: '3000', count: 3 } }

data [i] .count专门从每个项目获取计数.我需要这个for循环驻留在while循环中,以便对于每个项目我都可以得到它的计数并将其打印到表中.当for循环位于while循环之外(当前情况如何)时,我会获得正确的信息.我可以使表显示任何数据的唯一方法是将其设置为变量,然后仅将最新的数据打印到表中.但是,当我将那个 for 循环放入 while 循环中以便它创建另一个带有计数的 td 元素时,表格就会中断.

the data[i].count is specifically getting the count from each item. I need this for loop to live inside of the while loop so that for each item I can get the count of it and print it out into the table. When the for loop lives outside of the while loop(how it currently is) I get the correct information. The only way I can get the table to show any of that data is to set it to a variable which then only prints the latest piece of data into the table. But when I take that for loop and put it inside of the while loop so it creates another td element with the count, the table simply breaks.

有人知道如何最好的方法来将此计数信息打印到该表中吗?似乎for循环可以存在于while循环中,但是当我这样做时,代码/应用程序根本不满意.任何帮助是极大的赞赏.

Any idea how a best way to get this count information printing out into this table? It seems like the for loop could live inside the while loop but the code/application is not happy at all when I do that. Any help is greatly appreciated.

推荐答案

在while循环中,当前产品ID为:

Inside your while loop, the current product ID is:

var pID = results[i][0].productId;

要获取给定产品ID的 data 中的计数,请将其用作购物车条目字典中的键:

To get the count in data for a given product ID, use that as a key into the dictionary of cart entries:

var count = data[pID].count;

您无需遍历while循环的每个迭代中的每个条目;您只想输入当前产品ID.因此, for 循环不会为您提供帮助.只需索引字典即可.

You don't need to loop over every entry each iteration of the while loop; you just want to the entry for the current product ID. Thus, a for loop isn't going to help you. Just index into the dictionary.

更新while循环,使其看起来像这样:

Update the while loop to look like so:

  while(i < len){
    var pId = results[i][0].productId;
    table += '<tr>';
    table += '<td><img src='+results[i][0].filePath+' alt="An Image" class="thumbnail-img" /></td>';
    table += '<td id = "productName">'+results[i][0].productName+'</td>';
    table += '<td id = "'+results[i][0].productPrice+'">$'+results[i][0].productPrice+'</td>';
    table += '<td>'+data[pId].count+'</td>';
    table += '<td><button type="button" id="productDescription" class="btn btn-primary" name = "'+pId+'">Description</button></td>';
    table += '<td><button type="button" class="btn btn-success" id="updateCartBtn" name = "'+pId+'">Update</button></td>';
    table += '</tr>';
    i++;
  }

这篇关于如何在Node.js的while循环中正确使用for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆