为什么我的功能不能在我的控制台中打印反向数组?
var numbers = [1, 2, 3, 4, 5, 6, 7];
function swap(array) {
for (var i = 0; i < Math.floor(array / 2); i++) {
var temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
return array;
}
console.log(swap(numbers));
答案 0 :(得分:1)
此行Math.floor(array/ 2)
的问题。它必须是Math.floor(array.length / 2)
var numbers = [1, 2, 3, 4, 5, 6, 7];
function swap(array) {
for (var i = 0; i < Math.floor(array.length / 2); i++) {
var temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
return array;
}
console.log(swap(numbers));
答案 1 :(得分:0)
因为在你的for循环中,条件是i < Math.floor(array/2)
,而应该是i < Math.floor(array.length/2)
。由于.length
是具有数组长度的属性。
var numbers = [1,2,3,4,5,6,7];
function swap(array) {
for (var i = 0; i < Math.floor(array.length/2); i++) {
var temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length-1-i] = temp;
}
return array;
}
console.log(swap(numbers));
您也可以使用.reverse()
var numbers = [1,2,3,4,5,6,7];
console.log(numbers.reverse());