得到这个简单的例子:
const arr = [
{name: 'first', amount: 2},
{name: 'second', amount: 1},
{name: 'third', amount: 1}
]
const obj = {name: 'second', amount: 3}
for (let i = 0; i < arr.length; i++) {
if (arr[i].name === obj.name) {
arr[i].amount += obj.amount;
break;
} else {
arr.push(obj)
}
}
我想执行普通的for循环,期望的结果是,如果有一个对象与数组中的名称相同,那么只需将数量
相加,否则我想要 obj
被推送到列表中。
但实际上这两种情况都会发生。当我从 if 语句中跳出时,如何使 else 语句不运行?
最佳答案
如果找到数据集,您需要另一个变量 found
并将其设置为 true
。然后不要将实际数据集推送到数组。
基本上您需要访问所有元素并在最后决定是否将对象添加到数组中。
使用您的代码,您至少采取一个操作,或者更新实际的数据集结束导出,这仅在所需的 name
位于第一个元素中时有效,或者您将对象推送到大批。这一直发生到找到所需的数据集,或者没有更多元素可用为止。
const arr = [{ name: 'first', amount: 2 }, { name: 'second', amount: 1 }, { name: 'third', amount: 1 }];
const obj = { name: 'second', amount: 3 };
var found = false;
for (let i = 0; i < arr.length; i++) {
if (arr[i].name === obj.name) {
arr[i].amount += obj.amount;
found = true;
break;
}
}
if (!found) {
arr.push(obj);
}
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 无法干净地跳出 javascript 中的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54275131/