【问题标题】:How to add up true values from an array in Javascript? [duplicate]如何在Javascript中将数组中的真实值相加? [复制]
【发布时间】:2021-04-12 18:15:39
【问题描述】:

如何编写一个只将真值相加的函数?我试过了,但它不起作用:

const array1 = [true, true, true, false, true, true, true, true, true, false, true, false, true, 
false, false, true, true, true, true, false, false, true, true,];

const array2 = [];

function countSheeps(arrayOfSheep) {
  for (let i = 0; i < array1.length; i++) {
    if (array1[i] === true) continue;

    return console.log(array2.push(countSheeps(array1)));
  }
}

正如你所见,我是一个初学者,所以你的解释对我来说意味着一个世界。

【问题讨论】:

  • 将返回移出循环——它会导致你的循环提前结束
  • 我这样做了,结果发生了:Uncaught RangeError: Maximum call stack size exceeded.
  • @vladika 下面的代码将循环遍历array1,如果条件匹配它将把值推入array2
  • console.log(array1.filter(Boolean).length); --> 16
  • 这很好用。非常感谢!

标签: javascript arrays function


【解决方案1】:

const array1 = [true, true, true, false, true, true, true, true, true, false, true, false, true,
    false, false, true, true, true, true, false, false, true, true,];
const array2 = [];

for (i = 0; i < array1.length; i++) {
    if (array1[i] === true) {
        array2.push(array1[i]);
    }
}
console.log(array2);

【讨论】:

    【解决方案2】:

    如果我理解正确,你想countSheeps 统计并返回输入中trues 的数量。

    您的原始代码存在一些问题。

    1. 不计算 true 值,而是跳过它们 (if (array1[i] === true) continue)
    2. 您返回调用console.log的结果,而不是返回最终值,该结果返回undefined (return console.log(...))
    3. 您的函数在false 第一次出现后存在,因为您在for 循环内定义了return 语句。

    类似于你已经做过的,你可以做:

    const sheep = [true, true, true, false, true, true, true, true, true, false, true, false, true, false, false, true, true, true, true, false, false, true, true];
    
    function countSheep(arrayOfSheep) {
        let count = 0
        for (let i = 0; i < sheep.length; i++) {
            if (sheep[i] === true) count += 1;
        }
        return count
    }
    
    console.log(countSheep(sheep))
    
    // -> 16
    

    在函数内部,我首先初始化变量count,它保存输入数组中trues 的总量。在 for 循环中遇到值 true 的每次迭代后,都会更新此值。最后,在for循环之后,变量count被返回并记录到控制台。

    要在一行中解决问题,您可以这样做:

    console.log(sheep.filter(value =&gt; value === true).length)

    这首先创建数组的副本,过滤数组使其仅包含值true,最后计算数组的长度。

    【讨论】:

      【解决方案3】:

      试试这个先生

      let array1 = [true, true, true, false, true, true, true, true, true, false, true, false, true, 
      false, false, true, true, true, true, false, false, true, true,];
      console.log("this first condtion",array1);
      let search = true;
      var count = array1.reduce(function(n, val) {
          return n + (val === search);
      }, 0);
      console.log("result", count)

      【讨论】:

        猜你喜欢
        • 2020-08-25
        • 2021-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-30
        • 2021-06-29
        • 1970-01-01
        • 2021-11-21
        相关资源
        最近更新 更多