繁体   English   中英

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

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

go 如何循环遍历此数组以获取从所选音符开始的每一秒“音符”,例如从 F 开始并获得 f,a,c。 任何帮助将不胜感激:)

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

您可以使用余数运算符使用 findIndex 和过滤器

我假设你想环绕

如果我包装我得到 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))

如果这是您经常重复的操作,您可以 map 每个音符及其索引。 然后创建一个包含 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]

然后,创建一个 function 从映射器获取初始索引。 然后是下两个索引的项目

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

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

您可以使用模运算符,以便您的索引变量在达到 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]+",");
}

在某些情况下,还有另一种使用 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]+",")
);

注意: ; 在没有{}的 for 循环之后非常重要。

另一种方法是首先将数组的两个部分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+",");
}

您可以使用 for 循环并在要开始的元素的索引处开始循环。 例如,这将是 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