【问题标题】:If else/ for loops in JavaScriptJavaScript 中的 if else/for 循环
【发布时间】:2018-10-28 12:27:02
【问题描述】:

有什么方法可以使这个 if-else 语句泛化。现在,truthArray 包含从 t1 到 t4 的值。我正在寻找一种方法来为任意数量的值 t5、t6 等创建通用解决方案。我不知道如何告诉 for 循环根据真值数组的长度创建越来越多的嵌套 if 语句。谢谢。 代码说明: 首先,我想检查 t1 是否为真。如果是这样,那么 positionArray 中的第一个元素将是“左”。现在我想在 t1 已经确定为真时检查 t2 的值。如果 t2 为真,那么我将 positionArray 中的第二个元素设置为“右”。之后,我想在 t1 和 t2 已经为真时检查 t3 是否为真,并将 positionArray 的第三个元素设置为 left。然后我在 t1、t2、t3 都为真时检查 t4 是否为真,依此类推。因此, positionArray 的连续元素将是右,然后是左,然后是右,然后是左,依此类推。 现在如果 t1 不正确,那么我想从 t2 开始相同的过程。如果 t1 不为真,则位置数组的第一个元素将是未定义的。如果 t1 不为真而 t2 为真,则 positionArray 的第二个元素设置为“左”,连续的元素将是右、左、右等。 如果 t1 和 t2 都不为真,则该过程将从 t3 开始,依此类推..

            var truthArray = [t1, t2, t3, t4]; 
            var positionArray = [];
            var i;        
  
           
            if (truthArray[0] === true) {
                positionArray[0] = 'left';
                if (truthArray[1] === true) {
                    positionArray[1] = 'right';
                    if (truthArray[2] === true) {
                        positionArray[2] = 'left';
                        if (truthArray[3] === true) {
                            positionArray[3] = 'right';
                        }
                    }
                    else if (truthArray[3] === true) {
                        positionArray[3] = 'left';
                    }
                }
                else if (truthArray[2] === true) {
                    positionArray[2] = 'right';
                    if (truthArray[3] === true) {
                        positionArray[3] = 'left';
                    }
                }
                else if (truthArray[3] === true) {
                    positionArray[3] = 'right';
                }
            }
            else if (truthArray[1] === true) {
                positionArray[1] = 'left';
                if (truthArray[2] === true) {
                    positionArray[2] = 'right';
                    if (truthArray[3] === true) {
                        positionArray[3] = 'left';
                    }
                }
                else if (truthArray[3] === true) {
                    positionArray[3] = 'right';
                }
            }
            else if (truthArray[2] === true) {
                positionArray[2] = 'left';
                if (truthArray[3] === true) {
                    positionArray[3] = 'right';
                }
            }
            else if (truthArray[3] === true) {
                positionArray[3] = 'left';
            }
            

【问题讨论】:

  • if/else != 循环
  • 已更正。谢谢。
  • 我无法弄清楚底层逻辑是什么,所以我无法判断通用解决方案是什么。您能否概述一下您尝试实现的一般逻辑?
  • 为什么所有这些 IF 都是嵌套的?请编辑您的问题,并解释您要做什么。
  • 现在添加了解释。希望它能澄清我正在尝试做的事情。

标签: javascript for-loop if-statement


【解决方案1】:

希望对您有所帮助,如果您遇到任何问题,请告诉我

var truthArray = [false, false, true]; 
var positionArray = [];
var positionArrayValues = ['left','right'];
var offsetArray = [];
var start = 0, end = truthArray.length;      
function traverseFurther(index,positionArrayIndex) {
    if(index === end)
        return;
    if(truthArray[index] === true) {
        positionArray[index] = positionArrayValues[positionArrayIndex];
        traverseFurther(index + 1, positionArrayIndex === 0 ? 1 : 0);
    } else {
        traverseFurther(index + 1,positionArrayIndex);
    }
}
traverseFurther(start, 0);

【讨论】:

  • 稍作修改即可工作。只需要这样做 :positionArrayIndex %2 == 0 吗? 1:0。
【解决方案2】:

所以你想遍历truthValues 并构建一个positionArray where if (truthValue == false) add undefined to positionArray else add 'left''right'positionArray 这样'left''right' 总是交替?

你可以这样做。

    //fill truthArray with 10 random boolean values
    const truthArray = [];
    for (var i = 0; i < 10; i++) {
      truthArray.push(Math.random() > 0.5);
    }
    
    //calc(truthArray) and map the result (and truthInput) to make it easier to read
    const input = truthArray.map(t => t?'T':'F');
    const output = calc(truthArray).map(v => {
      if (v === 'left') return 'L';
      if (v === 'right') return 'R';
      if (v === undefined) return '-';
    });
    
    //display truthInput and result
    console.log('T is true, F is false');
    console.log('L is left, R is right, - is undefined');
    console.log(input.join());
    console.log(output.join());
    
    function calc(truthArray) {
      var trueCount = 0;
      const result = [];
      for (var truthVal of truthArray) {
        if (truthVal) {
          const position = (trueCount % 2 == 0)
            ? 'left'
            : 'right';
          result.push(position);
          trueCount++;
        } else {
          result.push(undefined);
        }
      }
      
      return result;
    }

【讨论】:

    【解决方案3】:

    您可以只映射检查并返回切换值或undefined

    它通过检查元素的值来工作,并接受带有对象和值posflip-flop。通过将pos 作为对象的property accessorpos 分配一个新值,此值会发生变化。

    rl = { right: 'left', left: 'right' }
    pos = 'right';
    pos = rl[pos]; // left
    pos = rl[pos]; // right
    pos = rl[pos]; // left
    pos = rl[pos]; // right
    // and so on ...
    

    如果元素不是truthy,则将undefined映射到结果集。

    var truthArray = [false, true, false, true],
        lr = { right: 'left', left: 'right' },
        pos = 'right',
        positionArray = truthArray.map(b => b ? pos = lr[pos] : undefined);
    
    console.log(positionArray);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    为了获得不同的模式,比如

    ['left', 'left', 'right', 'right']
    

    您可以增加索引并使用余数运算符对其进行调整,然后向右取一个位偏移值,该值除以 2 并返回一个整数值。

    var truthArray = [true, false, true, false, true, false, true, false, true],
        lr = ['left', 'right'],
        pos = 3,
        positionArray = truthArray.map(b => b ? lr[++pos, (pos %= 4) >> 1] : undefined);
    
    console.log(positionArray);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 你能解释一下这段代码发生了什么吗?它有效,但我不明白其中的逻辑。
    • @尼娜,明白了。谢谢。我们怎样才能让它交替为左、左、右、右而不是左、右、左、右?
    • 然后取一个索引变量并加一,并通过位移值(右移一,取整数)获取数组的值,并使用余数运算符进行调整。
    猜你喜欢
    • 1970-01-01
    • 2017-08-02
    • 2019-12-04
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2012-11-13
    相关资源
    最近更新 更多