var objectz = {};
objectz.a = 1;
objectz.b = 2
objArr = JSON.parse(localStorage.getItem('myItem'));
$.each(objArr, function(key,obj){
objectz.key = obj;
}
console.log(objectz);
我想将数组值添加到现有的obj中,得到{1,2,10},其中3到9被覆盖,我的错误在哪里?
最佳答案
除了语法错误(复制/粘贴错误?)之外,您的代码还通过objArr
进行迭代,并覆盖了"key"
(即objectz
)字面上称为objectz.key
的属性。您没有使用名为key
的函数参数迭代器。如果要使用称为key的函数参数更新objectz
,则可能要使用objectz[key]
。
很难猜测localStorage.getItem('myItem')
会返回什么。假设objArr = [{c: 3},{d: 4},{e: 5},{f: 6},{g: 7},{h: 8},{i: 9},{j: 10}]
,这是您的代码的更正版本:
http://jsbin.com/viwiko/edit?js,console
var objectz = {};
objectz.a = 1;
objectz.b = 2;
objArr = [{c: 3},{d: 4},{e: 5},{f: 6},{g: 7},{h: 8},{i: 9},{j: 10}];
//JSON.parse(localStorage.getItem('myItem'));
//$.each(objArr, function(key,obj){
// objectz.key = obj;//overwrites a property called 'key' for each element of objArr
//});
$.each(objArr, function(key,obj){
objectz[key] = obj;//key will be the zero based array index (i.e. 0 to 7 for the example data)
});
console.log(objectz);