对象数组的javascript迭代逻辑XOR?

时间:2018-04-19 09:19:22

标签: javascript reactjs logic

我有一个循环超过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,所以任何想法都将非常感谢,谢谢

2 个答案:

答案 0 :(得分:1)

  

是否有更快的方法可以简化这些if语句的过程?

当然,只需写一个声明

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

你也可以使用实际的XOR运算符^,但由于我们在这里使用布尔值,我更喜欢!=

答案 1 :(得分:0)

我更喜欢在Array.prototype.map上使用Array.prototype.filterArray.prototype.reduceArray.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;
 }, []);