繁体   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