英文:
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 = ['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')) {
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("A")
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 = ['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')) {
// The following will show that your test is actually testing
// for words that DON'T start with "A" (indexOf returns -1)
console.log(currentAnimal, currentAnimal.indexOf('A'));
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 = ['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) {
// By specifying that you need the index to be 0,
// you get the correct words:
console.log(currentAnimal, currentAnimal.indexOf('A'));
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 = ['Alligator', 'Fox', 'Armadillo', 'Tiger', 'Anteater', 'Raccoon', 'Chicken', 'Sheep', 'Dog', 'Antelope', 'Albatross', 'Cat', 'Alpaca', 'Ape', 'Anaconda'];
// Return a filtered array that only include words that start with "A" and get the length of tthat array.
console.log((animals.filter(word => word.indexOf("A") === 0)).length);
<!-- end snippet -->
答案2
得分: 0
实际上,您正在计算从1
或更大的值开始的-1
或其他值的索引。
String#indexOf
返回未找到时的-1
或找到的子字符串的索引。
要克服这个问题,您需要检查是否为零
animals[i].indexOf('A') === 0
或直接检查索引处的值
animals[i][0] === 'A'
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('A') === 0
or check the value at index directly
animals[i][0] === 'A'
or with String#startsWith
animals[i].startsWith('A')
<!-- 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 < animals.length; i++) {
console.log(i, animals[i], animals[i].indexOf('A'))
}
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论