【问题标题】:How do I build a long If Condition with an Array and the && condition?如何使用数组和 && 条件构建长 If 条件?
【发布时间】:2017-03-27 01:45:49
【问题描述】:

在我拥有之前:

      for (var i = 0; i < t1Children.length; i++) {
          return checkIdentical( t1Children[i], t2Children[i] );
      }

但我不知道如何使用 for 循环模式将每个“i”的 && 条件链接在一起。

以下内容按我想要的方式工作,但我需要继续手动添加 t2Children[2]、[3] 等。

      return ( ( checkIdentical( t1Children[0], t2Children[0] ) ) && ( checkIdentical( t1Children[1], t2Children[1] ) ) );

如何以一种可以将 && 链接在一起的方式进行迭代?有什么建议吗?

【问题讨论】:

  • 考虑将Array#every作为解决方案...var result = t1Children.every((t1, index) =&gt; checkIdentical(t1, t2Children[index]));
  • 不确定您要做什么,您是否尝试将一个数组中的每个元素与另一个数组中的每个元素进行比较?
  • 现在我想我明白你的意思了,看看答案

标签: javascript if-statement for-loop


【解决方案1】:

这个怎么样?

var result = true;
for (var i = 0; i < t1Children.length; i++) {
     result = result && checkIdentical( t1Children[i], t2Children[i] );
}

【讨论】:

  • 请注意,一旦变量结果变为假,我的答案应该停止调用 checkIdentical(),这可能会为否定答案节省一点时间,而对于所有相同的肯定结果来说仍然相同。如果必须为所有元素调用 checkIdentical(),请不要使用此答案。
【解决方案2】:
var allEqual = true;
for (var i = 0; i < array1.length; i++){
    if(array1[i] != array2[i]){
         allEqual = false;
         break;
    }
}
return allEqual;

这应该会起作用,因为如果所有元素都相等, allEqual 将保持为真,否则它将返回假

【讨论】:

    猜你喜欢
    • 2018-01-11
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 2015-08-24
    • 1970-01-01
    • 2016-09-05
    相关资源
    最近更新 更多