JavaScript统计数组中以'A'开头的字符串:代码为何少统计一个?
问题分析与解决
你的问题出在indexOf('A')的判断逻辑上:
indexOf('A')会返回字符'A'在字符串中的索引位置,如果字符串以'A'开头,返回值是0- 在JavaScript的if条件中,
0会被视为假值,所以第一个元素Alligator(索引0)不会被计入统计,这就导致总数少了1个,实际输出7而不是正确的8。
修复方案
方案1:修正indexOf的判断逻辑
直接判断indexOf('A')是否等于0,明确匹配开头的'A':
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]; // 判断是否以'A'开头,索引为0 if (currentAnimal.indexOf('A') === 0) { countAnimals += 1; } } console.log(countAnimals); // 输出8
方案2:使用更直观的startsWith()方法
ES6新增的startsWith()方法专门用来判断字符串是否以指定字符开头,可读性更强:
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); // 输出8
方案3:用数组filter()方法简化代码
如果不需要手动循环,可以直接用filter筛选符合条件的元素,再取长度,代码更简洁:
const animals = ['Alligator', 'Fox', 'Armadillo', 'Tiger', 'Anteater', 'Raccoon', 'Chicken', 'Sheep', 'Dog', 'Antelope', 'Albatross', 'Cat', 'Alpaca', 'Ape', 'Anaconda']; const countAnimals = animals.filter(animal => animal.startsWith('A')).length; console.log(countAnimals); // 输出8
内容的提问来源于stack exchange,提问作者kneeshuh
相关产品推荐
相关产品推荐

