首页 > 解决方案 > 错误,同时将元素从 mongodb 推送到数组

问题描述

使用 for 循环将元素推送到数组时出错

我的代码

router.get('/cart', verifyLogin, async (req, res) => {
 
  
    var products = await userHelpers.getCartProducts(req.session.user._id)
    console.log("quantity of 1 product:"+products[0].quantity);
    console.log("price of 1 product"+products[0].product.Price);
    console.log("length of cart:"+products.length);
    
 
  var numberOfProducts
  var proNum=[]
  var productsList=0


  for(numberOfProducts=0 ; numberOfProducts<=products.length; numberOfProducts++)
  
  { 
      console.log("price of product ****"+ products[numberOfProducts].product.Price);
    
      proNum[productsList]=products[numberOfProducts].product.Price
      productsList++
     
 
  }
  
 
   let totalValue=proNum.reduce((accumulator,currentValue)=>{
     return accumulator+currentValue
   },0)
  /////////

  
  
  res.render('user/cart', { products, user: req.session.user, totalValue })
  
}

打印的值时products[0].product.Price,它给出了正确的值。但是当涉及到 for 循环的主体时,它显示错误

错误

quantity of 1 product:3
price of 1 product100000
length of cart:3
price of product ****100000
price of product ****65000
price of product ****6509
(node:6604) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'product' of undefined
    at C:\Users\Bimal Boby\Desktop\E-commerce-Website\routes\user.js:107:71
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:6604) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6604) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

标签: javascriptnode.jsarraysfor-loopobject

解决方案


for(numberOfProducts=0 ; numberOfProducts<=products.length; numberOfProducts++)

应该

for(numberOfProducts=0 ; numberOfProducts < products.length; numberOfProducts++)

您应该使用<而不是<=因为<检查数组 0 1 2 而<=检查数组 0 1 2 3,而您只有 3 个产品。

发生这种情况是因为数组索引从 0 开始,而您.length是计数器。


推荐阅读