题目:
有一数组myArrray[1,2,3,4,5,6,7,8,9,’陆俊’,’是’,’最帅的人’],现在希望在控制台将其倒序输出;
解答:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数组内容翻转</title>
<script>
function swap(sourceArry) {
let newArray = new Array();//存放最后的转置后的数据
let i = 0;
for (const key of sourceArry) {
newArray[sourceArry.length - i - 1] = sourceArry[i++];
}
return newArray;
}
let myArray = [1,2,3,4,5,6,7,8,9,'陆俊','是','最帅的人'];
console.log(swap(myArray));
</script>
</head>
<body>
</body>
</html>
上面是非就地逆置的,下面这一种是就地:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数组内容就地逆置</title>
<script>
function swap(sourceArry) {
for (let i = 0; i < sourceArry.length; i++) {
sourceArry[i] = sourceArry[i] ^ sourceArry[sourceArry.length - i - 1];
}
return sourceArry;
}
let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, '陆俊', '是', '最帅的人'];
console.log(swap(myArray));
</script>
</head>+
<body>
</body>
</html>
其实这里也可以不写返回值,这里直接修改的就是原数组中的内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数组内容就地逆置</title>
<script>
function swap(sourceArry) {
for (let i = 0; i < sourceArry.length; i++) {
sourceArry[i] = sourceArry[i] ^ sourceArry[sourceArry.length - i - 1];
}
}
let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, '陆俊', '是', '最帅的人'];
console.log(myArray);
</script>
</head>+
<body>
</body>
</html>