为什么我的数组在向其追加值时会输出不同的结果?

问题描述 投票:-2回答:2

给定一个像animals = ['ant', 'bear', 'cat', 'dog', 'elephant', 'cat', 'fox', 'goat', 'cat'];这样的数组,我的任务是找出cat这个词出现的次数。

我可以执行以下功能并输出结果:

let catCounter = 0;
let result = [];

animals.filter(animal => {
  if (animal === 'cat') {
    catCounter++;
  } result.push(catCounter);
});

console.log(result);

这给了[ 0, 0, 1, 1, 1, 2, 2, 2, 3 ]

我只需要最终结果,这是3,我知道我可以通过这个console.log(catCounter);获得所需的结果。

请简要说明为什么会发生这种情况,如果有更好的方法来完成我的任务,我们将非常感激,如果可以提供。

javascript arrays loops
2个回答
1
投票

使用Array.push()方法,通过这样做,每次使用push()时都会向结果数组附加一个值。这解释了为什么它会导致这样的数组。

让我们通过迭代迭代。

假设以下动物阵列['cat', 'dog', 'chicken', 'cat']

On first loop  =>       increment catCounter (1) and push it to array => `[1]`
On second loop => don't increment catCounter (1) and push it to array => `[1, 1]`
On third loop  => don't increment catCounter (1) and push it to array => `[1, 1, 1]`
On fourth loop =>       increment catCounter (2) and push it to array => `[1, 1, 1, 2]`

如果你想计算你可以做多少只猫:

let catCounter = 0;

animals.forEach(animal => {
  if (animal === 'cat') {
    catCounter++;
  }
});

console.log(catCounter);

1
投票

这样做:

var arrayVal = ['ant', 'bear', 'cat', 'dog', 'elephant', 'cat', 'fox', 'goat', 'cat'];
console.log(arrayVal.filter(function(e){ if(e=='cat'){return e}}).length);
© www.soinside.com 2019 - 2024. All rights reserved.