错误,同时将元素从 mongodb 推送到数组

时间:2021-05-20 03:23:15

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

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

1 个答案:

答案 0 :(得分:0)

Sub loop1()
    'Dynamic range for cells with data
    Dim LastRow As Long
    LastRow = Worksheets("HU").Cells(Rows.Count, 2).End(xlUp).Row '
    LastRow1 = LastRow - 1
    Rng = "C1:D" & LastRow1
    matchrng = "C1:C" & LastRow1

    'Locate start cell in data
    alphabet_start = "G"
    locate_start = Application.Match(alphabet_start, matchrng, 0)

    'Determine end cell
    alphabet_end = "J"
    'WIP_end = Application.VLookup(alphabet_end, myrange, 2, False)
End Sub

应该

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

您应该使用 for(numberOfProducts=0 ; numberOfProducts < products.length; numberOfProducts++) 而不是 < 因为 <= 检查数组 0 1 2 而 < 检查数组 0 1 2 3,而您只有 3产品。

发生这种情况是因为数组索引从 0 开始,而您的 <= 是一个计数器。