[英]javascript iterative logical XOR for array of objects?
我有一个循环2个Feature对象数组并检查每个Feature的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来说相对较新,因此任何想法都会受到赞赏,谢谢
有没有更快的方法可以简化这些if语句的过程?
当然,只写一个语句
if (feature.active != originalFeatures[index].active) {
return changes.push({
name: feature.name,
change: feature.active ? 'Activated' : 'Deactivated'
});
}
您也可以使用实际的XOR运算符^
但是由于我们在这里使用布尔值,因此我更喜欢!=
。
我更喜欢使用Array.prototype.map
, Array.prototype.filter
和Array.prototype.reduce
超过Array.prototype.forEach
。
未经测试:
const changes = features.reduce((filtered, feature, index) => {
if (feature.active ^ originalFeatures[index].active) {
filtered.push({ name: feature.name, change: (feature.active) ? 'Activated' : 'Deactivated' }})
}
return filtered;
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.