如何使用递归将元素插入数组中的所有位置 - JavaScript?
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/1 0:12:17
我们需要声明一个函数,比如说 insertAllPositions,它接受两个参数 −
一个元素 x 和一个数组 arr。函数必须返回一个数组数组,每个数组对应于 arr,其中 x 插入到可能的位置。
也就是说,如果 arr 的长度为 N,则结果是一个包含 N + 1 个数组 −
例如,insertAllPositions(10, [1,2,3]) 的结果应该是 −
const output = [ [10,1,2,3], [1,10,2,3], [1,2,10,3], [1,2,3,10] ];
我们需要纯粹使用递归来编写此函数。
示例
以下是代码 −
const arr = [1, 2, 3];
const num = 10;
const insertAllPositions = (num, arr) => {
return arr.length ?
[[num, ...arr]]
.concat(insertAllPositions(num, arr.slice(1))
.map(el => {
return [arr[0]].concat(el);
})) :
[[num]]
};
console.log(insertAllPositions(num, arr));
输出
这将在控制台上产生以下输出 −
[ [ 10, 1, 2, 3 ], [ 1, 10, 2, 3 ], [ 1, 2, 10, 3 ], [ 1, 2, 3, 10 ] ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

