简体   繁体   English

JavaScript localStorage:如何使用 JSON.stringify 从保存的数组 object 解析方法

[英]JavaScript localStorage: how to parse method from saved array object using JSON.stringify

I have the following JavaScript code:我有以下 JavaScript 代码:

function Product(){

this.ProductName="";
this.Quantity=0;
this.Price=0;
this.Category="";
this.Total=function() {
    return this.Quantity *  this.Price;
  }
this.Discount=function() {
    return this.Total() *  0.25;
  }  
}

var Product = new Product();

Product.ProductName="Tipkovnica";
Product.Quantity=100;
Product.Price=150.5;
Product.Category="IT";

if(localStorage.Products){
    Products = JSON.parse(localStorage.getItem("Products"));
}
else
{
    var Products = [];  
}
Products.push(Product);
localStorage.setItem('Products', JSON.stringify(Products));

function RetrieveObjects(Products){
    for(var a=0;a<Products.length; a++){
        document.write("<br>Product Name: "+Products[a].ProductName);
        document.write("<br>Quantity: "+Products[a].Quantity);
        document.write("<br>Price: "+Products[a].Price);
        document.write("<br>Category: "+Products[a].Category);
        document.write("<br>Total: "+Products[a].Total());
        document.write("<br>Discount: "+Products[a].Discount());
    }
}

I made JSON.stringify to store array object in JSON.我制作了 JSON.stringify 以将数组 object 存储在 JSON 中。 Then, When I tried to loop object from array back from storage after JSON parse, I got error because methods Total() and Discount() were not recognized as methods.然后,当我尝试在 JSON 解析后从存储中循环返回数组中的 object 时,出现错误,因为方法Total()Discount()未被识别为方法。

Any idea why?知道为什么吗?

Thanks, Milan谢谢,米兰

Your function is using this but that is the global this which is the window object.您的 function 正在使用thisthis是全局的,即window object。

However, there is another problem, you cannot (or rather should not) store functions in JSON as there is no function data type.但是,还有另一个问题,您不能(或者不应该)将函数存储在 JSON 中,因为没有 function 数据类型。 You should calculate the values and store the result in your JSON.您应该计算值并将结果存储在 JSON 中。

var Product {

    productName: null,
    quantity: 0,
    price: 0,
    category: null,
    finalTotal: 0,
    discountedTotal: 0,
    total: function() {
        return this.quantity * this.price;
    },
    discount: function() {
        return this.total() * 0.25;
    }
}
var newProduct = Object.create(Product);

newProduct.productName = "Tipkovnica";
newProduct.quantity = 100;
newProduct.price = 150.5;
newProduct.category = "IT";
newProduct.finalTotal = newProduct.total();
newProduct.discountedTotal = newProduct.discount();


if (localStorage.Products) {
    Products = JSON.parse(localStorage.getItem("Products"));
    Products.push(newProduct);
} else {
    Products = [newProduct];
}

localStorage.setItem('Products', JSON.stringify(Products));

function RetrieveObjects(Products) {
    for (var a = 0; a < Products.length; a++) {
        document.write("<br>Product Name: " + Products[a].productName);
        document.write("<br>Quantity: " + Products[a].quantity);
        document.write("<br>Price: " + Products[a].price);
        document.write("<br>Category: " + Products[a].category);
        document.write("<br>Total: " + Products[a].finalTotal);
        document.write("<br>Discount: " + Products[a].discountedTotal);
    }
}

Because if you stringify the object, then all the methods are removed.因为如果你对 object 进行字符串化,那么所有的方法都会被删除。 Take a look at this: https://stackblitz.com/edit/typescript-2tfnkr看看这个: https://stackblitz.com/edit/typescript-2tfnkr

Not related hint: use the camelCase instead of PascalCase convention for all of the methods, properties and variables.不相关提示:对所有方法、属性和变量使用 camelCase 而不是 PascalCase 约定。 PascalCase should be used in class names, interfaces etc. PascalCase 应用于 class 名称、接口等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 LocalStorage 和 JSON.stringify JSON.parse - LocalStorage and JSON.stringify JSON.parse 如何在不使用“JSON.stringify”方法的情况下将javascript对象转换为json? - How to convert javascript object into json without using “JSON.stringify” method? 如何使用 JavaScript 在没有 JSON.stringify 的情况下将对象转换为字符串? - How to convert object to string without JSON.stringify using JavaScript? 如何在javascript文件中使用JSON.stringify()从node.js中检索对象? - How to retrieve an object from node.js using JSON.stringify() within a javascript file? 如何从 URLSearchParams JSON.stringify object? - How to JSON.stringify object from URLSearchParams? Javascript 深拷贝使用 JSON.parse 和 JSON.stringify - Javascript deep copy using JSON.parse and JSON.stringify Fabric.js-排除使用JSON.stringify()保存特定对象的方法; - Fabric.js - Exclude specific object from being saved using JSON.stringify(); 在Javascript对象上使用JSON.stringify插入反斜杠 - Using JSON.stringify on Javascript object inserts backslashes 我正在使用JSON.stringify(the_data)在localstorage中设置对象数组,现在如何重用此数据? - I am setting an array of objects in localstorage using JSON.stringify(the_data), how do I reuse this data now? 如何将 Javascript JSON.stringify() 转换为 PHP 数组 - How to convert Javascript JSON.stringify() to PHP Array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM