问题描述
创建一个名为car的对象:
Creating an object called 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);
-
设置对象并从localStorage中读取后进行字符串化:
Setting object and stringify after reading from localStorage:
localStorage.setItem('car',car);
car = localStorage.getItem('car');
car = JSON.stringify(car);
stringify后的汽车-----------------> file:///android_asset/www/...上的[object Object]
car after stringify-----------------> [object Object] at file:///android_asset/www/...
将对象字符串化并在其后将对象设置为localStorage: localStorage.setItem('car',JSON.stringify(car));car = localStorage.getItem('car');
Stringify object and Setting object to localStorage after it:localStorage.setItem('car',JSON.stringify(car));car = localStorage.getItem('car');
stringify后的汽车----------------->"{\" brand \:\" Skoda \,\" color \:\" Red \,\"year \":\"2012 \"}在file:///android_asset/www/...
car after stringify-----------------> "{\"brand\":\"Skoda\",\"color\":\"Red\",\"year\":\"2012\"}" at file:///android_asset/www/...
问题1:为什么在对对象进行字符串化时顺序会有所不同?
Question 1: Why does it make difference what is the order when you stringify the object?
问题2:为什么我不能使用像这样的字符串化对象:
Question 2: Why can't I use stringified object like that:
08-21 11:49:14.860: I/Web Console(9642): car after stringify-----------------> {"brand":"Skoda","color":"Red","year":"2012"}
console.log("car.brand ----->" + car.brand);car.name ----->未定义
console.log("car.brand----->" +car.brand);car.name----->undefined
推荐答案
根据我的理解,一旦字符串化了对象,就无法使用它,因为它不再是对象.这是一个字符串.
From my understanding you can't use your stringified object once it's been stringified because it's no longer an object. It's a String.
因此,当您尝试对字符串执行 car.brand
时,没有属性 brand
.
So when you try to do car.brand
on the string there is no property brand
.
我个人认为,这样做是好的习惯.
Personally, good practice in my opinion would be to do.
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);
这意味着汽车对象现在不是字符串而是对象.
This means the car object is now not a string but an object.
执行此操作时,还要使用stringify写入本地存储,并使用parse读取.
When doing this also write to local storage using stringify and read using parse.
这篇关于使用stringify设置对象并将其获取到本地存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!