从中间出过程阵列 [英] Process array from the middle out
问题描述
我需要经过一个数组从中间outwords。
I need to go through an array from the middle outwords.
var array = [a,b,c,d,e];
我需要在这个以打印:
C,D,B,E,A
I would need to print in this order: c,d,b,e,a
我已经劈成两半的阵列,首先向前,然后倒退这已经是一个进步,但我真的需要去一边一个,直到两边的数组的结尾。
I have already split the array in half, first going forward and then going backwards which is already an improvement, but I really need to go one on each side till the end of the array on each side.
说我想在中间开始。我以前的循环语句,条件下,我似乎无法找出第三部分切换一边一个增量。
Say I want to start in the middle. I have the following before the loop statement, condition, and I can't seem to figure out the third part to switch one on each side incrementally.
for (var i = Math.floor(array.length/2); i >= 0 || i < array.length; i?){
//Do Something here.
}
有谁知道如何做到这一点?
很显然,我似乎无法在这种情况下,以测试。
Does anyone know how to do this? Obviously I can't seem to test this in this condition.
感谢
我修改下面答案(非常感谢)拿出这个功能。它允许从阵列中的任何地方开始,然后选择要去的方向。我相信它可以更文笔优美。也有对错误的索引号的安全。
I modified the answer below (Thanks so much) to come up with this function. It allows to start from anywhere in the array and choose the direction to go. I am sure it could be written more elegantly. There is also a safety for wrong index numbers.
var array = ["a", "b", "c", "d", "e"];
function processArrayMiddleOut(array, startIndex, direction){
if (startIndex < 0){
startIndex = 0;
}
else if ( startIndex > array.length){
startIndex = array.lenght-1;
};
var newArray = [];
var i = startIndex;
if (direction === 'right'){
var j = i +1;
while (j < array.length || i >= 0 ){
if (i >= 0) newArray.push(array[i]);
if (j < array.length) newArray.push(array[j]);
i--;
j++;
};
}
else if(direction === 'left'){
var j = i - 1;
while (j >= 0 || i < array.length ){
if (i < array.length) newArray.push(array[i]);
if (j >= 0) newArray.push(array[j]);
i++;
j--;
};
};
return newArray;
}
var result = processArrayMiddleOut(array, 2, 'left');
alert(result.toString());
http://jsfiddle.net/amigoni/cqCuZ/
推荐答案
两个计数器,一个往上走,等下去:
Two counters, one going up, other going down:
var array = ["a", "b", "c", "d", "e"];
var newArray = [];
var i = Math.ceil(array.length/2);
var j = i - 1;
while (j >= 0)
{
newArray.push(array[j--]);
if (i < array.length) newArray.push(array[i++]);
}
这篇关于从中间出过程阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!