是否有更简单的方法来交换数组中的两个元素?
var a = list[x], b = list[y];
list[y] = a;
list[x] = b;
是否有更简单的方法来交换数组中的两个元素?
var a = list[x], b = list[y];
list[y] = a;
list[x] = b;
当前回答
如果你因为某些原因不允许使用就地交换,这里有一个map的解决方案:
函数swapElements(数组,源,dest) { 返回源=== dest ? Array:阵列。Map ((item, index) => index === source ? 数组[dest]: index === dest ? 数组[来源]:item); } Const arr = ['a', 'b', 'c']; const s1 = swapElements(arr, 0,1); Console.log (s1[0] === 'b'); Console.log (s1[1] === 'a'); const s2 = swapElements(arr, 2,0); Console.log (s2[0] === 'c'); Console.log (s2[2] === 'a');
下面是快速复制粘贴的typescript代码:
function swapElements(array: Array<any>, source: number, dest: number) {
return source === dest
? array : array.map((item, index) => index === source
? array[dest] : index === dest
? array[source] : item);
}
其他回答
这是一个精简版 arr中i1和i2的值互换
arr.slice(0,i1).concat(arr[i2],arr.slice(i1+1,i2),arr[i1],arr.slice(i2+1))
function moveElement(array, sourceIndex, destinationIndex) {
return array.map(a => a.id === sourceIndex ? array.find(a => a.id === destinationIndex): a.id === destinationIndex ? array.find(a => a.id === sourceIndex) : a )
}
let arr = [
{id: "1",title: "abc1"},
{id: "2",title: "abc2"},
{id: "3",title: "abc3"},
{id: "4",title: "abc4"}];
moveElement(arr, "2","4");
对于数值,可以使用按位的异或来避免临时变量
list[x] = list[x] ^ list[y];
list[y] = list[y] ^ list[x];
list[x] = list[x] ^ list[y];
或算术和(注意,这仅适用于x + y小于数据类型的最大值时)
list[x] = list[x] + list[y];
list[y] = list[x] - list[y];
list[x] = list[x] - list[y];
下面是一个不会改变列表的一行代码:
let newList =对象。赋值([],列表,{[x]:列表[y], [y]:列表[x]})
(使用了2009年问题发布时还没有的语言功能!)
好吧,你不需要缓冲两个值-只有一个:
var tmp = list[x];
list[x] = list[y];
list[y] = tmp;