【问题标题】:How to create a "on" array from a "switch on" array and "switch off" array in javascript如何在javascript中从“开启”数组和“关闭”数组创建“开启”数组
【发布时间】:2021-05-27 11:52:06
【问题描述】:

我有两个表示时间序列的数组,一个描述开关何时打开,另一个描述开关何时关闭。最后,我想要一个状态数组来描述对象何时打开或关闭。

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]

即使物体已经打开,开关也可以打开,即使物体已经关闭,开关也可以关闭。 如何在 javascript 中高效地做到这一点?

【问题讨论】:

  • 到目前为止你尝试过什么? Stackoverflow 的存在是为了回答具体问题,而不是为您编写代码。
  • @Thomas 它不起作用,因为您需要使用以前的值。请注意,有几个 (0, 0, 1) 对,最后有一个 (0, 0, 0) 对。

标签: javascript arrays arraylist


【解决方案1】:

这是一种方法。它使用 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);

【讨论】:

    【解决方案2】:

    只要是全一和零,或者truefalse,你就可以进行简单的位运算:

    基本上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(" "));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 2022-12-15
      • 1970-01-01
      相关资源
      最近更新 更多