gpt4 book ai didi

javascript - javascript 中使用 math.floor 函数反转数组

转载 作者:行者123 更新时间:2023-12-03 02:23:46 28 4
gpt4 key购买 nike

为什么我的函数不在控制台中打印反转的数组?

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));

最佳答案

此行 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));

关于javascript - javascript 中使用 math.floor 函数反转数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49045607/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com