简体   繁体   English

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

[英]javascript iterative logical XOR for array of objects?

I have a function that loops over 2 arrays of Feature objects and checks if each Feature's active property has changed. 我有一个循环2个Feature对象数组并检查每个Feature的active属性是否已更改的函数。 So far I have this: 到目前为止,我有这个:

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) The code doesn't work, there's a logic error I can't seem to bust. A)代码不起作用,有一个逻辑错误我似乎无法解决。 After changing the active state of a single feature, the function outputs changes as an array of half the features being 'Activated'. 更改单个功能部件的激活状态后,该功能将输出changes为“已激活”功能部件的一半的阵列。 Note I have asserted the two input arrays as containing the correct objects and property values before the function is run. 注意在运行函数之前,我断言两个输入数组包含正确的对象和属性值。

B) is there a faster built in function that could simplify the process from these if statements? B)是否有更快的内置函数可以简化这些if语句的过程?

Am relatively new to javascript so any ideas would be greatly appreciated, thanks 对javascript来说相对较新,因此任何想法都会受到赞赏,谢谢

is there a faster way that could simplify the process from these if statements? 有没有更快的方法可以简化这些if语句的过程?

Sure, just write a single statement 当然,只写一个语句

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

You could also use the actual XOR operator ^ but since we are working with booleans here I prefer != . 您也可以使用实际的XOR运算符^但是由于我们在这里使用布尔值,因此我更喜欢!=

I prefer the use of Array.prototype.map , Array.prototype.filter and Array.prototype.reduce over Array.prototype.forEach . 我更喜欢使用Array.prototype.mapArray.prototype.filterArray.prototype.reduce超过Array.prototype.forEach

Untested: 未经测试:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM