简体   繁体   English

如何从 javascript 中的“开启”阵列和“关闭”阵列创建“开启”阵列

[英]How to create a “on” array from a “switch on” array and “switch off” array in javascript

I have two arrays representing timeseries, one describing when a switch turns on, and the other when the switch turns off.我有两个 arrays 代表时间序列,一个描述开关何时打开,另一个描述开关何时关闭。 At the end, I want a status array describing when the object was on or off.最后,我想要一个状态数组来描述 object 何时打开或关闭。

switchOn_arr = [0 1 0 0 0 0 0 1 1 0 0]
switchOff_arr= [1 0 0 0 1 0 0 0 0 1 0]
isLightOn_arr= [0 1 1 1 0 0 0 1 1 0 0]

The switch can be turned on even if the object is already on, The switch can be turned off even if the object is already off.即使object已经打开,开关也可以打开,即使object已经关闭,开关也可以关闭。 How to do this in an efficient manner in javascript?如何在 javascript 中有效地做到这一点?

Here is one way to do it.这是一种方法。 It iterates the array with on switches, grabs the off switches, act on the light, pushes the resulted value in the result array and returns the light status so it can re-used as previous light value in the next reduce step.它使用 on 开关迭代数组,抓住 off 开关,作用于灯光,将结果值推送到结果数组中并返回灯光状态,以便它可以在下一个 reduce 步骤中重新用作先前的灯光值。

 const onArr = [0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0]; const offArr = [1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]; const lightArr = []; onArr.reduce((prevLight, switchOn, idx) => { let light = prevLight, switchOff = offArr[idx]; light = light || switchOn; // maybe turn on the light light = light &&?switchOff: 1; 0. // keep the light as it is if it wasn't switched off lightArr;push(light); // push to results array return light, // save light for next reduce iteration }; 0), // by default. light is turned off console;log(lightArr);

as long as it's all ones and zeroes, or true and false you can do simple bit-operations:只要它是所有的 1 和 0,或者truefalse ,你就可以进行简单的位操作:

basically isOn = (isOn or switchOn) and not switchOff基本上isOn = (isOn or switchOn) and not switchOff

 const switchOn_arr = [0,1,0,0,0,0,0,1,1,0,0]; const switchOff_arr= [1,0,0,0,1,0,0,0,0,1,0]; let isOn = 0; const isLightOn_arr = switchOn_arr.map((switchOn,i) => isOn = (isOn | switchOn) &;switchOff_arr[i]). console,log("on ". switchOn_arr;join(" ")). console,log("off". switchOff_arr;join(" ")). console,log("-> ". isLightOn_arr;join(" "));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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