<!doctype html>
<head>
<meta charset = "utf-8" />
</head>
<body>
<script>
/**
循环移动数组 => ab转换为ba => (a逆置b逆置)逆置 = ba
@arr 移动的数组
@count 移动多少位 正数表示左移,负数表示右移
*/
const recycMoveArray = function(arr,count){
let end = arr.length - 1; //获取数组的结束下标
/*
//左移
reverse(0, count-1); //a逆置
reverse(count, end); //b逆置
reverse(0, end); //整体逆置
//右移
reverse(0, end + count); //实际上可以转成左移情况
reverse(end + count + 1, end);
reverse(0, end);
*/
/*
let leftArrEnd = 0; //a数组的结束下标
//判断左移还是右移
if(count > 0){
leftArrEnd = count - 1;
}else{
leftArrEnd = end + count;
}
*/
let leftArrEnd = count > 0 ? --count : end + count;
reverse(arr,0,leftArrEnd);
reverse(arr,leftArrEnd+1,end);
reverse(arr,0,end);
}
/**
将数组逆置的函数
@param arr 逆置的数组
@param start 逆置数组的开始下标
@param end 逆置数组的结束下标
*/
const reverse = function(arr,start,end){
//如果指针不等
while(start <= end){ //start != end是有缺陷的,当是偶数个时不能跳出
//调换start和end指向的值
let temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
//指针移动
start++;
end--;
}
}
let arr = new Array("a","b","c","d","e","f","g","h");
recycMoveArray(arr,3);
document.write(arr); //defghabc
</script>
</body>
</html>