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

问题描述 投票:0回答:1

我有以下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());
    }
}

我制作了JSON.stringify以将数组对象存储在JSON中。然后,当我尝试在JSON解析后从存储中将数组中的对象循环回存储时,由于方法Total()Discount()被识别为方法而出现错误。

知道为什么吗?

谢谢,米兰

javascript json local-storage session-storage
1个回答
0
投票

因为如果对对象进行字符串化,则将删除所有方法。看看这个:https://stackblitz.com/edit/typescript-2tfnkr

© www.soinside.com 2019 - 2024. All rights reserved.