javascript - 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 );
我在最后一行出现错误,我不知道为什么。请帮助,在此先感谢您。
解决方案
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);
});
});
}
}
推荐阅读
- python - 这是使用goslate的方式吗
- php - 从 Laravel 5.7 (Eloquent) 中的多个表中获取数据
- c# - 在 C# 中未正确检测到正则表达式模式
- algorithm - 作业调度变化
- c# - Serilog 时间戳 @t 不是 UTC 时间
- mysql - mysql在哪里运行命令
- java - 当我使用 ContextHierarchy 时,没有可用的“org.springframework.security.config.annotation.ObjectPostProcessor”类型的限定 bean
- c# - CA2000 在 ConcurrentDictionary 中保存引用时发出警告
- c - 如何使用 malloc 捕获程序员错误?
- excel - 将一个类成员从一个子传递到另一个