使用stringify设置和获取对象到本地存储?

Sam*_*ami 8 javascript object local-storage stringify

创建一个名为car的对象:

function car(temp){

    this.brand=temp[0];
    this.color=temp[1];
    this.year=temp[2];
}

var temp = ['Skoda', 'Red', '2012'];
car = new car(temp);
Run Code Online (Sandbox Code Playgroud)
  1. 从localStorage读取后设置对象和字符串化:

    localStorage.setItem('car',car);
    car = localStorage.getItem('car');
    car = JSON.stringify(car);
    
    Run Code Online (Sandbox Code Playgroud)

    stringify后的汽车-----------------> [object Object]在file:/// android_asset/www/...

  2. Stringify对象和设置对象后面的localStorage: localStorage.setItem('car',JSON.stringify(car)); car = localStorage.getItem('car');

stringify后的汽车----------------->"{\"品牌\":\"斯柯达\",\"颜色\":\"红色","年份\":\"2012 \"}"at file:/// android_asset/www/...

问题1:为什么它会使字符串化对象时的顺序有所不同?

问题2:为什么我不能像这样使用字符串化对象:

08-21 11:49:14.860: I/Web Console(9642): car after stringify----------------->     {"brand":"Skoda","color":"Red","year":"2012"}
Run Code Online (Sandbox Code Playgroud)

console.log("car.brand ----->"+ car.brand); car.name ----->未定义

LmC*_*LmC 17

根据我的理解,一旦它被字符串化,你就不能使用你的字符串化对象,因为它不再是一个对象.这是一个字符串.

因此,当您尝试对car.brand字符串执行操作时,没有属性brand.

就个人而言,我认为良好的做法是做.

 function car(temp){
     this.brand=temp[0];
     this.color=temp[1];
     this.year=temp[2];
 }

 var temp = ['Skoda', 'Red', '2012'];
 car = new car(temp);

 localStorage.setItem('car',JSON.stringify(car)); 
 car = localStorage.getItem('car');
 car = JSON.parse(car);
Run Code Online (Sandbox Code Playgroud)

这意味着汽车对象现在不是字符串而是对象.

执行此操作时,还使用stringify写入本地存储并使用parse读取.


fre*_*rik 10

你不能存储JavaScript对象是localStorage,看到这个问题.

所以使用你的第二个选项.首先对存储它的对象进行字符串化.然后将其拾起并解析为javascript对象.

localStorage.setItem('car',JSON.stringify(car));
carString = localStorage.getItem('car');
car = JSON.parse(carString);
console.log(car.brand); // Skoda
Run Code Online (Sandbox Code Playgroud)