javascript循環移動數組

<!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>
相關文章
相關標籤/搜索