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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM