Zno*_*man 1 javascript arrays foreach for-loop object
尝试为数组中的每个对象添加一个 ID。如果 id 已经存在,则 id 会加 1,尝试实现自动递增功能。问题是,使用此函数时,每个对象在 foreach 语句内运行 for 循环时都会获得相同的 ID,或者obj.id of undefined
如果循环在外部运行,则无法读取。
function addId(arr, obj) {
obj.id;
arr.forEach(function(obj) {
obj.id = 0;
return obj.id;
});
for(var i = 0; i <= arr.length; i++) {
if(obj.id == obj.id) obj.id++;
}
};
Run Code Online (Sandbox Code Playgroud)
您的代码存在一些问题。首先obj.id;
什么也不做。所以你应该摆脱它。同样在你内部,forEach
你将值0
作为 id 分配给每个对象,但在第二个循环中,你要检查作为参数传入的 id 是否obj
与其本身相同,因此检查将始终产生true
并且然后你增加传入的 id obj
。
因此,在将 id 属性设置为 后,您永远不会操作数组中的对象0
。
您可以使用索引作为 id 的值。
另外,如果需要,您可以考虑使用类似的方法Object.assign
来防止更改数组内的原始对象。
function addId(arr) {
return arr.map(function(obj, index) {
return Object.assign({}, obj, { id: index });
});
};
// test
const input = [ { a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }];
const output = addId(input);
console.log(output);
Run Code Online (Sandbox Code Playgroud)