JavaScript: counting strings that begin with 'A' within an array – why is my code not counting them all?

huangapple go评论151阅读模式
英文:

JavaScript: counting strings that begin with 'A' within an array - why is my code not counting them all?

问题

我正在尝试编写一个循环,用于计算变量'animals'中以字母'A'开头的字符串数量。总共有8个,但控制台只记录了7个,我不确定为什么。

const animals = ['Alligator', 'Fox', 'Armadillo', 'Tiger', 'Anteater', 'Raccoon', 'Chicken', 'Sheep', 'Dog', 'Antelope', 'Albatross', 'Cat', 'Alpaca', 'Ape', 'Anaconda'];
let countAnimals = 0;

for (let i = 0; i < animals.length; i++) {
  const currentAnimal = animals[i]
  if (currentAnimal.startsWith('A')) {
    countAnimals += 1
  }
}

console.log(countAnimals)
英文:

I'm trying to code a loop which counts the amount of strings within the variable 'animals' that begin with an 'A'. There are 8, but the console only logs 7 and I'm not sure why.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const animals = [&#39;Alligator&#39;, &#39;Fox&#39;, &#39;Armadillo&#39;, &#39;Tiger&#39;, &#39;Anteater&#39;, &#39;Raccoon&#39;, &#39;Chicken&#39;, &#39;Sheep&#39;, &#39;Dog&#39;, &#39;Antelope&#39;, &#39;Albatross&#39;, &#39;Cat&#39;, &#39;Alpaca&#39;, &#39;Ape&#39;, &#39;Anaconda&#39;];
  let countAnimals = 0;

  
  for (let i = 0; i &lt; animals.length; i++) {
    const currentAnimal = animals[i]
    if (currentAnimal.indexOf(&#39;A&#39;)) {
        countAnimals += 1
    }
  }
  
  console.log(countAnimals)

<!-- end snippet -->

答案1

得分: 4

你的循环实际上是在计算不以"A"开头的单词。这是因为当你有一个以"A"开头的单词时,indexOf("A")将返回0,并导致你的if条件看起来像这样:

if (0)

由于0是“假值”(falsey),因此在隐式转换为布尔值false时,实际上是在测试以"A"开头的单词时,你的if条件会评估为:

if (false)

由于false永远不会等于true,所以当遇到不以"A"开头的单词时,你不会进入if语句的"真"分支。

我们可以通过添加一些日志来证明这一点:

const animals = ['Alligator', 'Fox', 'Armadillo', 'Tiger', 'Anteater', 'Raccoon', 'Chicken', 'Sheep', 'Dog', 'Antelope', 'Albatross', 'Cat', 'Alpaca', 'Ape', 'Anaconda'];
let countAnimals = 0;

for (let i = 0; i < animals.length; i++) {
  const currentAnimal = animals[i]
  if (currentAnimal.indexOf('A')) {
    // 下面的日志将显示你实际上在测试不以"A"开头的单词(indexOf返回-1)
    console.log(currentAnimal, currentAnimal.indexOf('A'));
    countAnimals += 1
  }
}

console.log(countAnimals)

你需要检查返回的索引是否为0。

const animals = ['Alligator', 'Fox', 'Armadillo', 'Tiger', 'Anteater', 'Raccoon', 'Chicken', 'Sheep', 'Dog', 'Antelope', 'Albatross', 'Cat', 'Alpaca', 'Ape', 'Anaconda'];
let countAnimals = 0;

for (let i = 0; i < animals.length; i++) {
  const currentAnimal = animals[i]
  if (currentAnimal.indexOf('A') === 0) {
    // 通过指定需要索引为0,你可以得到正确的单词:
    console.log(currentAnimal, currentAnimal.indexOf('A'));
    countAnimals += 1
  }
}

console.log(countAnimals)

你还可以使用Array.prototype方法之一来完成此操作,这些方法专门用于这类操作:

const animals = ['Alligator', 'Fox', 'Armadillo', 'Tiger', 'Anteater', 'Raccoon', 'Chicken', 'Sheep', 'Dog', 'Antelope', 'Albatross', 'Cat', 'Alpaca', 'Ape', 'Anaconda'];

// 返回一个只包含以"A"开头的单词的过滤后的数组,并获取该数组的长度。
console.log((animals.filter(word => word.indexOf("A") === 0)).length);
英文:

Your loop is actually counting the words that don't start with "A". This is because when you have a word that does start with "A", indexOf(&quot;A&quot;) will return 0 and it causes your if condition to look like this:

if(0)

Since 0 is "falsey" and therefore implicilty converts to the Boolean false, it turns out that words that start with "A" actually cause your if condition to evaluate as if it was written like this:

if(false)

And since false is never true, you don't enter the true branch with words that start with "A", however with any other word that doesn't start with "A", you will get a non-zero number back and non-zero numbers are "truthy" and convert to the Boolean true when implicitly converted, so you wind up entering the true branch of the if statement when words that DON'T start with "A" are encountered.

We can see this by adding a little logging:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const animals = [&#39;Alligator&#39;, &#39;Fox&#39;, &#39;Armadillo&#39;, &#39;Tiger&#39;, &#39;Anteater&#39;, &#39;Raccoon&#39;, &#39;Chicken&#39;, &#39;Sheep&#39;, &#39;Dog&#39;, &#39;Antelope&#39;, &#39;Albatross&#39;, &#39;Cat&#39;, &#39;Alpaca&#39;, &#39;Ape&#39;, &#39;Anaconda&#39;];
  let countAnimals = 0;
  
  for (let i = 0; i &lt; animals.length; i++) {
    const currentAnimal = animals[i]
    if (currentAnimal.indexOf(&#39;A&#39;)) {
        // The following will show that your test is actually testing
        // for words that DON&#39;T start with &quot;A&quot; (indexOf returns -1)
        console.log(currentAnimal, currentAnimal.indexOf(&#39;A&#39;));
        countAnimals += 1
    }
  }
  
  console.log(countAnimals)

<!-- end snippet -->

You need to check the returned index to see if it is 0.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const animals = [&#39;Alligator&#39;, &#39;Fox&#39;, &#39;Armadillo&#39;, &#39;Tiger&#39;, &#39;Anteater&#39;, &#39;Raccoon&#39;, &#39;Chicken&#39;, &#39;Sheep&#39;, &#39;Dog&#39;, &#39;Antelope&#39;, &#39;Albatross&#39;, &#39;Cat&#39;, &#39;Alpaca&#39;, &#39;Ape&#39;, &#39;Anaconda&#39;];
  let countAnimals = 0;
 
  for (let i = 0; i &lt; animals.length; i++) {
    const currentAnimal = animals[i]
    if (currentAnimal.indexOf(&#39;A&#39;) === 0) {
        // By specifying that you need the index to be 0,
        // you get the correct words:
        console.log(currentAnimal, currentAnimal.indexOf(&#39;A&#39;));
        countAnimals += 1
    }
  }
  
  console.log(countAnimals)

<!-- end snippet -->

You can also accomplish this using one of the Array.prototype methods, which are geared towards these kinds of operations:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const animals = [&#39;Alligator&#39;, &#39;Fox&#39;, &#39;Armadillo&#39;, &#39;Tiger&#39;, &#39;Anteater&#39;, &#39;Raccoon&#39;, &#39;Chicken&#39;, &#39;Sheep&#39;, &#39;Dog&#39;, &#39;Antelope&#39;, &#39;Albatross&#39;, &#39;Cat&#39;, &#39;Alpaca&#39;, &#39;Ape&#39;, &#39;Anaconda&#39;];

// Return a filtered array that only include words that start with &quot;A&quot; and get the length of tthat array.
console.log((animals.filter(word =&gt; word.indexOf(&quot;A&quot;) === 0)).length);

<!-- end snippet -->

答案2

得分: 0

实际上,您正在计算从1或更大的值开始的-1或其他值的索引。

String#indexOf 返回未找到时的-1或找到的子字符串的索引。

要克服这个问题,您需要检查是否为零

animals[i].indexOf('A') === 0

或直接检查索引处的值

animals[i][0] === 'A'

或使用 String#startsWith

animals[i].startsWith('A')
const animals = ['Alligator', 'Fox', 'Armadillo', 'Tiger', 'Anteater', 'Raccoon', 'Chicken', 'Sheep', 'Dog', 'Antelope', 'Albatross', 'Cat', 'Alpaca', 'Ape', 'Anaconda'];

for (let i = 0; i < animals.length; i++) {
    console.log(i, animals[i], animals[i].indexOf('A'))
}
英文:

Actually, you are counting indices of -1 or other values from 1 or greater.

String#indexOf returns -1 for not found or the index of the found substring.

To overcome this, you need to check with zero

animals[i].indexOf(&#39;A&#39;) === 0

or check the value at index directly

animals[i][0] === &#39;A&#39;

or with String#startsWith

animals[i].startsWith(&#39;A&#39;)

<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const animals = ['Alligator', 'Fox', 'Armadillo', 'Tiger', 'Anteater', 'Raccoon', 'Chicken', 'Sheep', 'Dog', 'Antelope', 'Albatross', 'Cat', 'Alpaca', 'Ape', 'Anaconda'];

for (let i = 0; i &lt; animals.length; i++) {
    console.log(i, animals[i], animals[i].indexOf(&#39;A&#39;))
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月29日 23:05:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76582317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定