js实现turnright
实现向右旋转(turnRight)功能
在JavaScript中,实现向右旋转通常涉及数组或矩阵的操作。以下是几种常见场景的实现方法:
数组元素向右旋转
将一个数组的元素向右旋转指定步数:
function rotateRight(arr, steps) {
const len = arr.length;
steps = steps % len;
return arr.slice(-steps).concat(arr.slice(0, -steps));
}
// 示例
const arr = [1, 2, 3, 4, 5];
console.log(rotateRight(arr, 2)); // 输出 [4, 5, 1, 2, 3]
二维矩阵顺时针旋转90度
将N×N矩阵顺时针旋转90度(即向右旋转):
function rotateMatrix(matrix) {
const n = matrix.length;
for (let i = 0; i < n / 2; i++) {
for (let j = i; j < n - i - 1; j++) {
let temp = matrix[i][j];
matrix[i][j] = matrix[n-j-1][i];
matrix[n-j-1][i] = matrix[n-i-1][n-j-1];
matrix[n-i-1][n-j-1] = matrix[j][n-i-1];
matrix[j][n-i-1] = temp;
}
}
return matrix;
}
// 示例
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(rotateMatrix(matrix));
// 输出 [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
更简洁的矩阵旋转方法
通过转置然后反转每一行实现顺时针旋转:
function rotateMatrixClean(matrix) {
// 转置矩阵
for (let i = 0; i < matrix.length; i++) {
for (let j = i; j < matrix[0].length; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
// 反转每一行
matrix.forEach(row => row.reverse());
return matrix;
}
DOM元素旋转
使用CSS transform实现DOM元素的右旋转:

function rotateElementRight(element, degrees) {
element.style.transform = `rotate(${degrees}deg)`;
}
// 示例
const box = document.getElementById('myBox');
rotateElementRight(box, 90); // 向右旋转90度
注意事项
- 对于数组旋转,需要考虑步数大于数组长度的情况,使用取模运算处理
- 矩阵旋转算法的时间复杂度通常是O(n²)
- 原地旋转矩阵会修改原数组,如果需要保留原数组应先创建副本
- DOM元素旋转使用的是CSS变换,不会改变元素在文档流中的实际位置






