我正在尝试在数组上执行for循环,并能够在特定索引上启动该循环,并在数组上循环x次。
const array = ['c','d','e','f','g','a','b','c']
我想循环8个从我希望的任何索引开始的索引。从array [4](g)开始的示例将返回
'g','a','b','c','c','d','e','f'
这是我到目前为止尝试过的
const notes = ['c','d','e','f','g','a','b','c']
var res = []
for (var i = 4; i < notes.length; i++) {
res.push(notes[i])
}
console.log(res)
答案 0 :(得分:6)
您可以使用%模运算符。
const getArray = (array, index) => {
const result = [];
const length = array.length;
for (let i = 0; i < length; i++) {
result.push(array[(index + i) % length]);
}
return result;
};
答案 1 :(得分:0)
简单方法。
var notes = ['c','d','e','f','g','a','b','c'];
function looparr(arr, start)
{
var res = [], start = start || 0;
for(var index = start, length=arr.length; index<length; index++)
{
res.push(arr[index]);
index == (arr.length-1) && (index=-1,length=start);
}
return res;
}
console.log(looparr(['c','d','e','f','g','a','b','c'], 0));
console.log(looparr(['c','d','e','f','g','a','b','c'], 2));
console.log(looparr(['c','d','e','f','g','a','b','c'], 4));
console.log(looparr(['c','d','e','f','g','a','b','c']));
答案 2 :(得分:0)
以下非常简单的解决方案:)
当i 享受:)let array = ['c','d','e','f','g','a','b','c'];
var index = 4;
for(var i = 0; i < index; i++){
var letter1 = array.shift(i); // Remove from the start of the array
array.push(letter1); // Add the value to the end of the array
}
console.log(array);