创建一个名为 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 读取后设置对象并字符串化:
localStorage.setItem('car',car);
car = localStorage.getItem('car');
car = JSON.stringify(car);
字符串化后的汽车-----------------> [object Object] at file:///android_asset/www/...
Stringify 对象并在其后将对象设置为 localStorage:localStorage.setItem('car',JSON.stringify(car));
car = localStorage.getItem('car');
stringify后的车-----------------> "{\"品牌\":\"斯柯达\",\"颜色\":\"红色\",\"年份\":\"2012\"}" 位于 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"}
console.log("car.brand----->" +car.brand);
car.name----->未定义
根据我的理解,一旦字符串化对象被字符串化,你就不能使用它,因为它不再是一个对象。这是一个字符串。
所以当你尝试做的时候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);
这意味着汽车对象现在不是字符串而是对象。
执行此操作时,还使用 stringify 写入本地存储并使用 parse 读取。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)