如何迭代从中间拉取数组项的序列(例如:[0,1,2,3,4,5,6,7] -> 4 3 5 2 6 1 7 0)而不生成序列号数组?

问题描述 投票:0回答:2

例如,从数组中间拉出项目时:[0,1,2,3,4,5,6,7](长度为8)

const arr=[0,1,2,3,4,5,6,7];
while(arr.length>0){
  document.write(arr.splice(arr.length/2,1)+" ");
}

要拉取的项目索引的顺序是:4 3 5 2 6 1 7 0

但是现在我想迭代索引,但不修改原始数组,也不生成序列数组(主要是原始数组在实际代码中有点大,也想要一个更简单的算法),我该如何用 for 迭代它仅循环?我尝试过:(c=8)

for(let i=0,c=8,half=Math.floor(c/2);i<c;i++){
    document.write(half+Math.floor(i/2)+(i%2==0?1:-1)+" ");
}

输出是 5 3 6 4 7 5 8 6 而不是 4 3 5 2 6 1 7 0,这是不起作用的。

javascript arrays algorithm
2个回答
1
投票

i
从 0 开始时,相应的
Math.floor(i/2)
值序列从 0, 0 开始。您希望一开始只有一个 0,可以通过使用
Math.ceil
来实现,例如:

for(let i=0,c=8,half=Math.floor(c/2);i<c;i++){
    document.write(half+Math.ceil(i/2)*(i%2==0?1:-1)+" ");
}


0
投票

您可以看到它是如何正确工作的。您基本上是找到中间元素,然后走向数组的开头或结尾。早些时候你可以这样做,因为数组长度正在缩短,但现在你没有那么奢侈了。所以你必须模拟它。

你可以有一个方向标志,它告诉指针要去哪里。 您可以有一个步长变量,它告诉您从中心开始要走多少步。

const arr= [0,1,2,3,4,5,6];
let count = arr.length;
let step = 0;
let ogDir = arr.length % 2 ? -1 : 1;
let dir = ogDir;


while(count>0){
  count--;
  document.write(arr[Math.floor(arr.length/2) + (step * dir)]+" ");
  dir*=-1;
  if(dir === (-ogDir) || step === 0){
    step+=1;
  }
}

上面的代码完全符合您的要求,而无需更改数组。

© www.soinside.com 2019 - 2024. All rights reserved.