交换数组的第 k 个元素 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/5 11:56:17
我们需要编写一个 JavaScript 函数,该函数接受一个数字数组和一个数字,例如 k(k 必须小于或等于数组的长度)。
并且我们的函数应该将数组从开头开始的第 k 个元素替换为从末尾开始的第 k 个元素。
示例
以下是代码 −
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const swapKth = (arr, k) => {
const { length: l } = arr;
let temp;
const ind = k-1;
temp = arr[ind];
arr[ind] = arr[l-k];
arr[l-k] = temp;
};
swapKth(arr, 4);
console.log(arr);
swapKth(arr, 8);
console.log(arr);
输出
以下是控制台中的输出 −
[ 0, 1, 2, 6, 4, 5, 3, 7, 8, 9 ] [ 0, 1, 7, 6, 4, 5, 3, 2, 8, 9 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

