gpt4 book ai didi

javascript 对象数组的迭代逻辑异或?

转载 作者:行者123 更新时间:2023-12-03 02:03:26 28 4
gpt4 key购买 nike

我有一个函数,可以循环 2 个要素对象数组,并检查每个要素的 active 属性是否已更改。到目前为止我有这个:

const changes = [];

let index = 0;

features.forEach((feature) => {

if (feature.active && !originalFeatures[index].active) {
return changes.push({ name: feature.name, change: 'Activated' });
}

if (!feature.active && originalFeatures[index].active) {
return changes.push({ name: feature.name, change: 'Deactivated' });
}

index += 1;
});

A)代码不起作用,存在逻辑错误,我似乎无法解决。更改单个功能的事件状态后,该函数将 changes 输出为包含一半“已激活”功能的数组。注意,在函数运行之前,我已断言两个输入数组包含正确的对象和属性值。

B)是否有更快的内置函数可以简化这些 if 语句的流程?

我对 javascript 比较陌生,所以任何想法将不胜感激,谢谢

最佳答案

is there a faster way that could simplify the process from these if statements?

当然,只需写一条语句

if (feature.active != originalFeatures[index].active) {
return changes.push({
name: feature.name,
change: feature.active ? 'Activated' : 'Deactivated'
});
}

您还可以使用实际的 XOR 运算符 ^,但由于我们在这里使用 bool 值,所以我更喜欢 !=

关于javascript 对象数组的迭代逻辑异或?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49917281/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com