说我有阵列
{0, 1, 2, 3, 4}
或
{0, 1, 2, 3, 4, 5}
我记得有一种非常聪明的方法可以做到这一点。像
这样的东西i%array.length
答案 0 :(得分:4)
试试这个:
oppIndex = array.length - firstIndex - 1;
答案 1 :(得分:1)
array = {1, 2, 3, 4, 5}
idx = 0 /* 0 is the first array position with value of 1 */
IF array.length - idx - 1 > idx
RETURN array[ array.length - idx - 1 ] /* returns array[4] == 5 */
ELSE
RETURN undefined
array = {1, 2, 3, 4, 5}
idx = 2 /* 2 is the third array position with value of 3 */
IF array.length - idx - 1 > idx /* 5 - 2 - 1 == 2 which is NOT greater than 2 */
RETURN array[ array.length - idx - 1 ]
ELSE
RETURN undefined
答案 2 :(得分:0)
按照你的第一个逻辑示例......
if (array.length%2==0){
for (int i =0; i<array.length/2; i++){
syso("the opposite of "+ array[i] + " is " + array[array.length -1-i]
}
}
else {
for (int i =0; i<floor(array.length/2); i++){
syso("the opposite of "+ array[i] + " is " + array[array.length -1-i]
}
i = i+1
syso("the opposite of "+ array[i] +" is undefined"
}