简体   繁体   中英

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. So for example, if we ran the function with the word 'Saturday' and 'a' as below, it should log an array [1,6]. Instead it is logging [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.

String#indexOf returns the first found index, but if you take an index as second parameter it searches from this 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 .

 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'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM