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

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

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

问题

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

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


<details>
<summary>英文:</summary>

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


</details>


# 答案1
**得分**: 1

你可以使用 findIndex 和 filter 以及余数运算符。

我假设你想要循环处理。

如果我循环,我得到 f, a, c, e,如果不循环,我只得到 f, a,所以我猜你期望的输出可能缺少 `e`?

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

const findNotes = (startNote, gap) => {
  const start = notes.findIndex(note => note === startNote);
  if (start !== -1) return notes.slice(start).concat(notes.slice(0, start)).filter((note, i) => i % gap === 0);
  return "not found";
};
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 -->

let notes = [&#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;a&#39;, &#39;b&#39;];

const findNotes = (startNote,gap) =&gt; {
  const start = notes.findIndex(note =&gt; note === startNote)
  if (start !=-1) return notes.slice(start).concat(notes.slice(0,start)).filter((note,i) =&gt; i%gap===0)
  return &quot;not found&quot;
};
console.log(findNotes(&quot;f&quot;,2))

<!-- end snippet -->

答案2

得分: 1

以下是您要翻译的内容:

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

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

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

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

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

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

请注意,这是一段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.

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

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

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

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

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

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

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

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

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

console.log(...findNext(&#39;f&#39;))
console.log(...findNext(&#39;c&#39;))

<!-- end snippet -->

答案3

得分: 1

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

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

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

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

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

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

let notes = ['c','d','e','f','g','a','b'];
let startIndex = notes.indexOf('f');
notes = [
	...notes.slice(startIndex),
	...notes.slice(0, startIndex)
];

for (let i = 0; i < notes.length - 2; i += 2) {
	  let note = notes[i];
	  document.write(note+",");
}
英文:

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,):

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

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

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

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:

let notes = [&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;a&#39;,&#39;b&#39;];
let startIndex = notes.indexOf(&#39;f&#39;);
notes = [
	...notes.slice(startIndex),
	...notes.slice(0, startIndex)
];

for (let i = 0; i &lt; notes.length - 2; i += 2) {
	  let note = notes[i];
	  document.write(note+&quot;,&quot;);
}

答案4

得分: 0

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

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

let startIndex = 3; // 从 'f' 开始

for (let i = startIndex; i < notes.length; i += 2) {
  let note = notes[i];
  console.log(note);
}
英文:

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

let notes = [&#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;a&#39;, &#39;b&#39;];

let startIndex = 3; // start at &#39;f&#39;

for (let i = startIndex; i &lt; notes.length; i += 2) {
  let note = notes[i];
  console.log(note);
}

<!-- 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:

确定