【发布时间】: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