首页 > 解决方案 > TypeError:无法读取 nodeJS 中未定义的属性“findIndex”

问题描述

这是我的代码:

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 );

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

标签: javascriptarraysnode.js

解决方案


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);
                });
        });
    }
}

推荐阅读