我怎样才能退出循环?
How can I drop out of the loop?
我试着写一个可以将数组向左旋转的函数,例如1,2,3,4,5,6,7,8,9
然后转到 4、5、6、7、8、9、1、2、3。首先,我使用下面这个函数,但结果是 4,2,3,7,5,6,1,8,9。
因此,我认为它不会退出循环,因为它只在循环中执行一次。请问有人可以帮我吗?任何帮助,将不胜感激!提前致谢。
var a =[1,2,3,4,5,6,7,8,9];
var len =a.length;
for (i=0;i<3;i++ )
{
var b = a[i];
var j = i;
for(k=0;k<a.length;k++)
{
j+=3;
if(j<a.length)
{
a[i] = a[j];
i=j;
}
else {
j-=3;
a[j]=b;
break;
}
}
}
console.log(a);
我不确定您使用的方法,但使用 shift
和 push
将很容易实现:
var a =[1,2,3,4,5,6,7,8,9];
var len = a.length;
for (i = 0; i < 3; i++) {
a.push(a.shift());
}
console.log(a);
输出:
4,5,6,7,8,9,1,2,3
shift
从数组中删除 first 项。这里有一些docs。
push
将一个项目推到数组的 end 上。这里有一些docs。
如果你想要没有数组方法的算法,你可以这样做:
var a=[1,2,3,4,5,6,7,8,9];
console.log(a);
//Iteration of rotation (Here rotated left 3 times) this can be as many as you want.
for(let i=0;i<3;i++){
//Store 'First Member' and 'Last Index' of array
let last = a.length - 1;
let first = a[0];
//Loop to store every (n+1)th term to nth except the last one
for(let j=0;j<last;j++){
a[j] = a[j+1];
}
//Finally add first item to last index
a[last] = first;
}
console.log(a);
我试着写一个可以将数组向左旋转的函数,例如1,2,3,4,5,6,7,8,9 然后转到 4、5、6、7、8、9、1、2、3。首先,我使用下面这个函数,但结果是 4,2,3,7,5,6,1,8,9。 因此,我认为它不会退出循环,因为它只在循环中执行一次。请问有人可以帮我吗?任何帮助,将不胜感激!提前致谢。
var a =[1,2,3,4,5,6,7,8,9];
var len =a.length;
for (i=0;i<3;i++ )
{
var b = a[i];
var j = i;
for(k=0;k<a.length;k++)
{
j+=3;
if(j<a.length)
{
a[i] = a[j];
i=j;
}
else {
j-=3;
a[j]=b;
break;
}
}
}
console.log(a);
我不确定您使用的方法,但使用 shift
和 push
将很容易实现:
var a =[1,2,3,4,5,6,7,8,9];
var len = a.length;
for (i = 0; i < 3; i++) {
a.push(a.shift());
}
console.log(a);
输出:
4,5,6,7,8,9,1,2,3
shift
从数组中删除 first 项。这里有一些docs。
push
将一个项目推到数组的 end 上。这里有一些docs。
如果你想要没有数组方法的算法,你可以这样做:
var a=[1,2,3,4,5,6,7,8,9];
console.log(a);
//Iteration of rotation (Here rotated left 3 times) this can be as many as you want.
for(let i=0;i<3;i++){
//Store 'First Member' and 'Last Index' of array
let last = a.length - 1;
let first = a[0];
//Loop to store every (n+1)th term to nth except the last one
for(let j=0;j<last;j++){
a[j] = a[j+1];
}
//Finally add first item to last index
a[last] = first;
}
console.log(a);