如何在JS中从索引开始循环遍历数组

huangapple go评论93阅读模式
英文:

How to loop through an array starting at an index in JS

问题

  1. 如何循环遍历该数组以获取从选择的音符开始的每第二个音符,例如从 F 开始获取 fac。任何帮助将不胜感激 :)

让音符 = ['c', 'd', 'e', 'f', 'g', 'a', 'b'];

  1. <details>
  2. <summary>英文:</summary>
  3. How would one go about looping through this array to get every second &quot;note&quot; starting at the note of choice eg start at F and get f,a,c. Any help would be greatly appricated :)

let notes = ['c','d','e','f','g','a','b'];

  1. </details>
  2. # 答案1
  3. **得分**: 1
  4. 你可以使用 findIndex 和 filter 以及余数运算符。
  5. 我假设你想要循环处理。
  6. 如果我循环,我得到 f, a, c, e,如果不循环,我只得到 f, a,所以我猜你期望的输出可能缺少 `e`?
  7. ```js
  8. let notes = ['c', 'd', 'e', 'f', 'g', 'a', 'b'];
  9. const findNotes = (startNote, gap) => {
  10. const start = notes.findIndex(note => note === startNote);
  11. if (start !== -1) return notes.slice(start).concat(notes.slice(0, start)).filter((note, i) => i % gap === 0);
  12. return "not found";
  13. };
  14. console.log(findNotes("f", 2));
英文:

You can use findIndex and filter using remainder operator

I assume you want to wrap around

If I wrap I get f,a,c,e If not I get f,a, so I assume your expected output was missing the e ?

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. let notes = [&#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;a&#39;, &#39;b&#39;];
  2. const findNotes = (startNote,gap) =&gt; {
  3. const start = notes.findIndex(note =&gt; note === startNote)
  4. if (start !=-1) return notes.slice(start).concat(notes.slice(0,start)).filter((note,i) =&gt; i%gap===0)
  5. return &quot;not found&quot;
  6. };
  7. console.log(findNotes(&quot;f&quot;,2))

<!-- end snippet -->

答案2

得分: 1

以下是您要翻译的内容:

如果这是您经常重复的操作,您可以将每个音符与其索引进行映射。然后创建一个包含音符的两个副本的数组,以便轻松地以循环方式获取下一个值。

  1. let notes = ['c', 'd', 'e', 'f', 'g', 'a', 'b'],
  2. indexMap = notes.reduce((map, n, i) => map.set(n, i), new Map),
  3. twoNotes = [...notes, ...notes]

然后,创建一个函数,该函数从映射器获取初始索引。然后获取下一个2个索引处的项。

  1. function findNext(note) {
  2. const index = indexMap.get(note)
  3. return [ twoNotes[index], twoNotes[index+2], twoNotes[index+4] ]
  4. }

或者,如果您将来需要更多的索引,您可以将其制作为通用函数,并将索引数组作为参数获取。

  1. function findNext(note) {
  2. const index = notesIndex.get(note)
  3. return [0, 2, 4].map(i => twoNotes[i + index])
  4. }

请注意,这是一段JavaScript代码,用于处理音符和获取下一个音符的值。如果您需要进一步的解释或帮助,请告诉我。

英文:

If this is an operation that you repeat often, you can map each note with its index. Then create an array with 2 copies of notes to easily get next values in a circular manner.

  1. let notes = [&#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;a&#39;, &#39;b&#39;],
  2. indexMap = notes.reduce((map, n, i) =&gt; map.set(n, i), new Map),
  3. twoNotes = [...notes, ...notes]

Then, create a function which gets the initial index from the mapper. And then items at the next 2 indices

  1. function findNext(note) {
  2. const index = indexMap.get(note)
  3. return [ twoNotes[index], twoNotes[index+2], twoNotes[index+4] ]
  4. }

or, if you want more indices in the future, you can make it generic one and get the indices array as an argument.

  1. function findNext(note) {
  2. const index = notesIndex.get(note)
  3. return [0, 2, 4].map(i =&gt; twoNotes[i + index])
  4. }

<!-- begin snippet: js hide: true console: true babel: false -->

<!-- language: lang-js -->

  1. let notes = [&#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;a&#39;, &#39;b&#39;],
  2. indexMap = notes.reduce((map, n, i) =&gt; map.set(n, i), new Map),
  3. twoNotes = [...notes, ...notes]
  4. function findNext(note) {
  5. const index = indexMap.get(note)
  6. return [0, 2, 4].map(i =&gt; twoNotes[i + index])
  7. }
  8. console.log(...findNext(&#39;f&#39;))
  9. console.log(...findNext(&#39;c&#39;))

<!-- end snippet -->

答案3

得分: 1

你可以使用模运算符,使你的索引变量在达到音符数组的长度后重新从0开始(输出 f,a,c,):

  1. let notes = ['c','d','e','f','g','a','b'];
  2. let startIndex = notes.indexOf('f');
  3. for (let i = startIndex; i !== startIndex-1; i = (i + 2) % notes.length) {
  4. document.write(notes[i]+",");
  5. }

还有另一种在某些情况下非常高效的方法,使用for循环...

  1. let notes = ['c','d','e','f','g','a','b'];
  2. let startIndex = notes.indexOf('f') - 2;
  3. for (
  4. let i = startIndex;
  5. i !== startIndex-1;
  6. (i = (i + 2) % notes.length) == document.write(notes[i]+",")
  7. );

注意:在没有{}的情况下,for循环之后非常重要要加上 ;

另一种方法是先将数组的两部分按正确的顺序“切片”:

  1. let notes = ['c','d','e','f','g','a','b'];
  2. let startIndex = notes.indexOf('f');
  3. notes = [
  4. ...notes.slice(startIndex),
  5. ...notes.slice(0, startIndex)
  6. ];
  7. for (let i = 0; i < notes.length - 2; i += 2) {
  8. let note = notes[i];
  9. document.write(note+",");
  10. }
英文:

You can use the modulo operator so that your index variable wraps around to 0 once it reaches the length of the notes array(outputs f,a,c,):

  1. let notes = [&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;a&#39;,&#39;b&#39;];
  2. let startIndex = notes.indexOf(&#39;f&#39;);
  3. for (let i = startIndex; i !== startIndex-1; i = (i + 2) % notes.length)) {
  4. document.write(notes[i]+&quot;,&quot;);
  5. }

There is another super performant way using the for loop in some cases...

  1. let notes = [&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;a&#39;,&#39;b&#39;];
  2. let startIndex = notes.indexOf(&#39;f&#39;)-2;
  3. for (
  4. let i = startIndex;
  5. i !== startIndex-1;
  6. (i = (i + 2) % notes.length)==document.write(notes[i]+&quot;,&quot;)
  7. );

Note: the ; is very important after the for loop without {}.

Another method would be to slice the two parts of the array into the proper order first:

  1. let notes = [&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;a&#39;,&#39;b&#39;];
  2. let startIndex = notes.indexOf(&#39;f&#39;);
  3. notes = [
  4. ...notes.slice(startIndex),
  5. ...notes.slice(0, startIndex)
  6. ];
  7. for (let i = 0; i &lt; notes.length - 2; i += 2) {
  8. let note = notes[i];
  9. document.write(note+&quot;,&quot;);
  10. }

答案4

得分: 0

你可以使用一个for循环,并从你想要开始的元素的索引开始循环。例如,这将输出:'f', 'a'

  1. let notes = ['c', 'd', 'e', 'f', 'g', 'a', 'b'];
  2. let startIndex = 3; // 从 'f' 开始
  3. for (let i = startIndex; i < notes.length; i += 2) {
  4. let note = notes[i];
  5. console.log(note);
  6. }
英文:

You can use a for loop and start the loop at the index of the element you want to start at. For example this will output: &#39;f&#39;, &#39;a&#39;.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. let notes = [&#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;a&#39;, &#39;b&#39;];
  2. let startIndex = 3; // start at &#39;f&#39;
  3. for (let i = startIndex; i &lt; notes.length; i += 2) {
  4. let note = notes[i];
  5. console.log(note);
  6. }

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年1月9日 14:59:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054017.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定