和我们用到的Array.reverse()效果一样
function reverse(arr){
for(let i=0;i<arr.length/2;i++){
let temp = arr[i]
arr[i] = arr[arr.length-1-i]
arr[arr.length-1-i] = temp
}
return arr
}
const demo = [1,2,3,4,5,6]
reverse(demo)
// [6, 5, 4, 3, 2, 1]
说明
const demo = [1,2,3,4,5,6]
先看下交换的规则
demo[0] = demo[5] 6-1-0
demo[1] = demo[4] 6-1-1
demo[2] = demo[3] 6-1-2
(6:数组的长度)
(1:由于是把下角标进行互换,所以要减1)
(0 1 2 :是对应前方元素的下角标)