簡體   English   中英

如何記錄每個數組項的索引?

[英]How can I log the index of each array item?

我是一個初學者,正在努力完成這個練習。 誰能告訴我為什么控制台將兩個字符的索引都記錄為 1。我希望它每次出現在單詞中時都記錄字符“a”。 因此,例如,如果我們運行 function 並使用以下單詞“星期六”和“a”,它應該記錄一個數組 [1,6]。 相反,它正在記錄 [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');

您可以直接從循環中獲取索引i

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

一種不使用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');

一種更簡單的方法是過濾索引。

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM