简体   繁体   English

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

[英]How to loop through an array starting at an index in JS

How would one go about looping through this array to get every second "note" starting at the note of choice eg start at F and get f,a,c. go 如何循环遍历此数组以获取从所选音符开始的每一秒“音符”,例如从 F 开始并获得 f,a,c。 Any help would be greatly appricated:)任何帮助将不胜感激:)

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

You can use findIndex and filter using remainder operator您可以使用余数运算符使用 findIndex 和过滤器

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 ?如果我包装我得到 f,a,c,e 如果不是我得到 f,a, 所以我假设你预期的 output 缺少e

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

If this is an operation that you repeat often, you can map each note with its index.如果这是您经常重复的操作,您可以 map 每个音符及其索引。 Then create an array with 2 copies of notes to easily get next values in a circular manner.然后创建一个包含 2 个注释副本的数组,以便以循环方式轻松获取下一个值。

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

Then, create a function which gets the initial index from the mapper.然后,创建一个 function 从映射器获取初始索引。 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 => twoNotes[i + index])
}

 let notes = ['c', 'd', 'e', 'f', 'g', 'a', 'b'], indexMap = notes.reduce((map, n, i) => map.set(n, i), new Map), twoNotes = [...notes, ...notes] function findNext(note) { const index = indexMap.get(note) return [0, 2, 4].map(i => twoNotes[i + index]) } console.log(...findNext('f')) console.log(...findNext('c'))

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, ):您可以使用模运算符,以便您的索引变量在达到 notes 数组的长度后回绕到 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]+",");
}

There is another super performant way using the for loop in some cases...在某些情况下,还有另一种使用 for loop的超高性能方法......

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]+",")
);

Note: the ;注意: ; is very important after the for loop without {} .在没有{}的 for 循环之后非常重要。

Another method would be to slice the two parts of the array into the proper order first:另一种方法是首先将数组的两个部分slice正确的顺序:

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 a for loop and start the loop at the index of the element you want to start at.您可以使用 for 循环并在要开始的元素的索引处开始循环。 For example this will output: 'f', 'a' .例如,这将是 output: 'f', 'a'

 let notes = ['c', 'd', 'e', 'f', 'g', 'a', 'b']; let startIndex = 3; // start at 'f' for (let i = startIndex; i < notes.length; i += 2) { let note = notes[i]; console.log(note); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM