[英]How can I log the index of each array item?
I'm a beginner and struggling with this exercise.我是一个初学者,正在努力完成这个练习。 Can anyone tell me why the console is logging the index of both characters as 1. I want it to log the character 'a' every time it appears in the word.
谁能告诉我为什么控制台将两个字符的索引都记录为 1。我希望它每次出现在单词中时都记录字符“a”。 So for example, if we ran the function with the word 'Saturday' and 'a' as below, it should log an array [1,6].
因此,例如,如果我们运行 function 并使用以下单词“星期六”和“a”,它应该记录一个数组 [1,6]。 Instead it is logging [1, 1].
相反,它正在记录 [1, 1]。
const subLength = (word, letter) => { let wordArray = word.split(""); let indexArray = [] for (i = 0; i < wordArray.length; i++) { if (wordArray[i] === letter) { indexArray.push(wordArray.indexOf(letter)); } } console.log(indexArray); } subLength('Saturday', 'a');
You could take the index i
from the loop directly.您可以直接从循环中获取索引
i
。
String#indexOf
returns the first found index, but if you take an index as second parameter it searches from this position. String#indexOf
返回第一个找到的索引,但如果您将索引作为第二个参数,它会从此 position 搜索。
const subLength = (word, letter) => { let wordArray = word.split(""); let indexArray = []; for (let i = 0; i < wordArray.length; i++) { // take let here too if (wordArray[i] === letter) { indexArray.push(i); } } console.log(indexArray); } subLength('Saturday', 'a');
An approach without using split
.一种不使用
split
的方法。
const subLength = (word, letter) => { let indexArray = []; for (let i = 0; i < word.length; i++) { if (word[i] === letter) indexArray.push(i); } console.log(indexArray); }; subLength('Saturday', 'a');
A simpler method would be to filter over the indexes.一种更简单的方法是过滤索引。
const subLength = (word, letter) => [...Array(word.length).keys()].filter(i => word[i] === letter); console.log(subLength('Saturday', 'a'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.