【问题标题】:TypeError: Cannot read property 'findIndex' of undefined in nodeJSTypeError:无法读取 nodeJS 中未定义的属性“findIndex”
【发布时间】:2020-09-30 00:48:44
【问题描述】:

这是我的代码:

const path = require('path');
const fs = require('fs');
let cart = { products: [], totalPrice: 0};
let jsonFilePath = path.join(path.dirname(process.mainModule.filename),
'data',
'cart.json'
);

module.exports = class Cart {
    static addProductToCart( productId, productPrice) {
        fs.readFile(jsonFilePath, (err, cartData) => {
            if(err){
                console.error(err);
            } else {
                cart = JSON.parse(cartData);
            }   
                const existingProductIndex = cart.products.findIndex(product => product.id === productId );

我在最后一行出现错误,我不知道为什么。请帮忙,在此先感谢您。

【问题讨论】:

  • 在您遇到错误的代码行之前控制 cart.products
  • 请分享购物车 json 和您从程序获得的输出
  • 感谢您的帮助@Deep Kakkar,感谢您对帮助我的关心,但我找到了解决方案,由于此购物车未获取产品,我使用 [] 而不是 {} .再次感谢

标签: javascript arrays node.js


【解决方案1】:
const fs=require('fs');
const path = require('path');
const p = path.join(path.dirname(process.mainModule.filename), 'data', 'cart.json');

module.exports=class Cart{
    static addProduct(id,productPrice){
        //Fetch the previous cart
        fs.readFile(p,(err,fileContent)=>{
            let cart={products:[],totalPrice:0};
                if(!err)
                {
                    cart=JSON.parse(fileContent);
                }
                //Analyze the cart=>Find Existing Product
                const existingProductIndex=cart.products.findIndex(x=>x.id===id);
                const existingProduct = cart.products[existingProductIndex];
                let updatedProduct;
                //Add New Product/increase Quantity
                if (existingProduct)
                {
                    updatedProduct={...existingProduct};
                    updatedProduct.qty = updatedProduct.qty+1;
                    cart.products={...cart.products};
                    cart.products[existingProductIndex]=updatedProduct;
                }
                else{
                    updatedProduct={id:id,qty:1};
                    cart.products = [...cart.products,updatedProduct];
                }
                cart.totalPrice = cart.totalPrice+ +productPrice;
                fs.writeFile(p, JSON.stringify(cart),(err)=>{
                    console.log(err);
                });
        });
    }
}

【讨论】:

  • 一般来说,如果答案包含对代码的用途的解释,以及为什么在不介绍其他人的情况下解决问题的原因,答案会更有帮助。
猜你喜欢
  • 1970-01-01
  • 2017-03-06
  • 2022-09-23
  • 2022-11-29
  • 2017-08-30
  • 2017-10-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
相关资源
最近更新 更多