【问题标题】:Error , while pushing element from mongodb to an array错误,同时将元素从 mongodb 推送到数组
【发布时间】:2021-08-09 07:16:41
【问题描述】:

使用 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.

【问题讨论】:

    标签: javascript node.js arrays for-loop object


    【解决方案1】:
    for(numberOfProducts=0 ; numberOfProducts<=products.length; numberOfProducts++)
    

    应该是

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

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

    这是因为数组索引从 0 开始,而您的 .length 是一个计数器。

    【讨论】:

      猜你喜欢
      • 2017-03-16
      • 2021-12-03
      • 2013-09-27
      • 1970-01-01
      • 2017-06-17
      • 2016-01-20
      • 2018-04-11
      • 2020-08-02
      • 1970-01-01
      相关资源
      最近更新 更多