如何计算数组中真值的数量?

How do I count the number of truth values in array?

我正在为一些逻辑问题苦苦挣扎,但我想我已经接近了。有没有办法从布尔数组中获取真值的数量?

  const checkedState = [true, false, true]

  function handleCourseProgress() {
    //for each value that is true in the array...
    checkedState.forEach((value) => {
      //if the value is true...
      if (value === true) {
        //count and total them up here....
        setCourseProgress(//return the count//);
      }
    });
  }

filtertrue 和 return 数组长度的元素。

const one = [false, true, true];
const two = [true, true, true];
const three = [false, false, false, false];

function trueElements(arr) {
  return arr.filter(b => b).length;
}

console.log(trueElements(one));
console.log(trueElements(two))
console.log(trueElements(three))

const checkedState = [false, true, false, true, true]

const count = checkedState.filter((value) => value).length
// Cleaner way
const anotherCount = checkedState.filter(Boolean).length

console.log(count)
console.log(anotherCount)

基本上过滤数组并寻找真实值并检查数组的长度就可以解决问题,之后您可以使用正确的计数值调用 setCourseProgress(count)

另一种方式是[true, false, true].filter(x=>x).length

你可以使用简单的filter or reduce

过滤为你想要的值然后统计过滤后的长度:

const filterQuantity = checkedState.filter((x) => x === true).length;

Reduce 将处理每个条目并确定我们是否需要递增 if true:

const reduceQuantity = checkedState.reduce((previousValue, currentValue) => {
  return (currentValue) ? previousValue + 1 : previousValue;
}, 0);

片段:

const checkedState = [true, false, true];

const filterQuantity = checkedState.filter((x) => x === true).length;

const reduceQuantity = checkedState.reduce((previousValue, currentValue) => {
  return (currentValue) ? previousValue + 1 : previousValue;
}, 0);

console.info(filterQuantity, reduceQuantity);

最简单的方法是使用 reduce。这是例子。

const checkedState = [true, false, true]

const answer = checkedState.reduce((acc, val) => val ? acc + val : acc);

console.log(answer)