JavaScript数组元素交换原理、写法及适用场景问询
关于你用map实现数组元素交换的几个问题解答
1. map方法实现交换的底层原理及完整写法
底层原理
map 是数组的迭代方法,核心逻辑是遍历原数组的每一个元素,执行你传入的回调函数,把回调返回的结果依次存入新数组,最后返回这个新数组,原数组不会被修改。
你这段代码的交换逻辑是:
- 当索引是奇数(
index % 2 !== 0):取原数组中前一个位置(index-1)的元素作为新数组当前位置的值 - 当索引是偶数:
- 如果是数组最后一个元素且数组长度为奇数:保留原元素不动
- 否则:取原数组中后一个位置(
index+1)的元素作为新数组当前位置的值
本质上不是真的在原数组里交换元素,而是通过读取原数组的不同位置值,构建出一个“看起来像是交换过”的新数组。
完整写法(更易读版本)
把箭头函数拆成普通函数,三元表达式换成if-else,逻辑更清晰:
const swapNumbers = (numbers) => { const swap = numbers.map(function(x, index) { if (index % 2 !== 0) { // 奇数索引,取前一个元素 return numbers[index - 1]; } else { // 偶数索引 if (index === numbers.length - 1 && numbers.length % 2 !== 0) { // 最后一个元素且数组长度为奇数,保留自身 return numbers[index]; } else { // 取后一个元素 return numbers[index + 1]; } } }); console.log(swap); }; swapNumbers([1, 2, 3, 4]); // 输出 [2,1,4,3] swapNumbers([1, 2, 5, 6, 8]); // 输出 [2,1,6,5,8]
2. numbers[index + 1] 和赋值语句不等价
numbers[index + 1] 是读取数组对应索引位置的值,属于取值操作;而 numbers[index + 1] = numbers[index] 或 numbers[index + 1] = x 是给数组对应索引位置赋值,属于赋值操作,两者完全不是一回事。
举个例子:
const arr = [1,2]; console.log(arr[1]); // 取值,输出2 arr[1] = 3; // 赋值,把arr[1]改成3 console.log(arr); // 输出[1,3]
你的代码里只是读取原数组的对应值来生成新数组,根本没有修改原数组,这一点要搞清楚。
3. 这种索引写法的适用条件
numbers[index ± n] 这种通过索引读取数组元素的写法,不是map等ES6方法专属,普通for循环里完全可以用,只要保证计算后的索引在数组合法范围内(0 ≤ 索引 < 数组长度)就行。
比如用普通for循环实现同样的逻辑:
const swapNumbers = (numbers) => { const swap = []; for (let index = 0; index < numbers.length; index++) { if (index % 2 !== 0) { swap.push(numbers[index - 1]); } else { if (index === numbers.length - 1 && numbers.length % 2 !== 0) { swap.push(numbers[index]); } else { swap.push(numbers[index + 1]); } } } console.log(swap); }; swapNumbers([1,2,3,4]); // 同样输出[2,1,4,3]
内容的提问来源于stack exchange,提问作者E Alexis MT
相关产品推荐
相关产品推荐

