JS 数组逆序输出,即反转数组
1.for 倒序输出
var arr = [1, 2, 3]
for (var i = arr.length - 1; i >= 0; i--) {
console.log(arr[i]) // 3 2 1
}
2.pop
var arr = [1, 2, 3, 4];
var res = [];
for (let i = arr.length - 1;i >= 0; i--) {
console.log(i)
res.push(arr.pop())
}
console.log(res); // [4, 3, 2, 1]
3.for 元素前后调换
var arr = [1, 2, 3]
var temp;
for (let i = 0; i < arr.length / 2; i++) {
temp = arr[i];
arr[i] = arr[arr.length-1-i];
arr[arr.length-1-i] = temp;
}
console.log(arr) // [3, 2, 1]
4.reverse
var str = 'hi'
console.log(str.split('').reverse().join('')) // ih