克隆JavaScript对象的最有效方法是什么?我已经看到obj = eval(uneval(o));被使用,但这是非标准的,只有Firefox支持.
我做过类似的事情,obj = JSON.parse(JSON.stringify(o));但质疑效率.
我也看到了具有各种缺陷的递归复制功能.
我很惊讶没有规范的解决方案.
我想在HTML5中存储JavaScript对象localStorage,但我的对象显然正在转换为字符串.
我可以使用存储和检索原始JavaScript类型和数组localStorage,但对象似乎不起作用.他们应该吗?
这是我的代码:
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
console.log('typeof testObject: ' + typeof testObject);
console.log('testObject properties:');
for (var prop in testObject) {
console.log(' ' + prop + ': ' + testObject[prop]);
}
// Put the object into storage
localStorage.setItem('testObject', testObject);
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('typeof retrievedObject: ' + typeof retrievedObject);
console.log('Value of retrievedObject: ' + retrievedObject);
Run Code Online (Sandbox Code Playgroud)
控制台输出是
typeof testObject: object
testObject properties:
one: 1 …Run Code Online (Sandbox Code Playgroud)