简体   繁体   English

如何记录每个数组项的索引?

[英]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.

相关问题 如何遍历一个jQuery数组,然后一次输出一项(从索引0开始)? - How can I loop through a jquery array and then output each item (starting at index 0) one at a time? 我如何记录数组中正确元素的索引,答案不是 -1 - How can i log the index of the correct element in array with an answer that is NOT -1 如何添加 append 并加入数组中的每个项目? - How can I prepend, append and join each item in an array? 如何在每个循环中获取 Meteor 模板中数组的索引? - How can I get the index of an array in a Meteor template each loop? 我如何找到项目数组的索引,以使用JavaScript查找项目是否在数组中 - how can i find the index of an item array, to find if an item is in an array using javascript 如何使用for循环控制台记录阵列的每个项目? - How to use a for loop to console log each item of an array? 如何获取数组中项的索引? - How do I get the index of an item in an array? Firebase-如何按子项(而不是其索引号)保存每个对象项? - Firebase - How can I save each object item by a child slug, opposed to their index number? 如何使用Javascript将迭代器索引号附加到数组中的每个项目? - How to append an iterator index number to each item within an array with Javascript? 如何访问被点击项目的索引? - How can I access the index of the clicked item?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM