是否有更简单的方法来交换数组中的两个元素?
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;
当前回答
下面是一个不会改变列表的一行代码:
let newList =对象。赋值([],列表,{[x]:列表[y], [y]:列表[x]})
(使用了2009年问题发布时还没有的语言功能!)
其他回答
就地交换
// array methods
function swapInArray(arr, i1, i2){
let t = arr[i1];
arr[i1] = arr[i2];
arr[i2] = t;
}
function moveBefore(arr, el){
let ind = arr.indexOf(el);
if(ind !== -1 && ind !== 0){
swapInArray(arr, ind, ind - 1);
}
}
function moveAfter(arr, el){
let ind = arr.indexOf(el);
if(ind !== -1 && ind !== arr.length - 1){
swapInArray(arr, ind + 1, ind);
}
}
// dom methods
function swapInDom(parentNode, i1, i2){
parentNode.insertBefore(parentNode.children[i1], parentNode.children[i2]);
}
function getDomIndex(el){
for (let ii = 0; ii < el.parentNode.children.length; ii++){
if(el.parentNode.children[ii] === el){
return ii;
}
}
}
function moveForward(el){
let ind = getDomIndex(el);
if(ind !== -1 && ind !== 0){
swapInDom(el.parentNode, ind, ind - 1);
}
}
function moveBackward(el){
let ind = getDomIndex(el);
if(ind !== -1 && ind !== el.parentNode.children.length - 1){
swapInDom(el.parentNode, ind + 1, ind);
}
}
交换数组中两个连续的元素
array.splice(IndexToSwap,2,array[IndexToSwap+1],array[IndexToSwap]);
这似乎还可以....
var b = list[y];
list[y] = list[x];
list[x] = b;
不管用
var b = list[y];
意味着变量b将在作用域的其余部分出现。这可能会导致内存泄漏。不太可能,但还是最好避免。
也许把这个放到array。prototype。swap中是个好主意
Array.prototype.swap = function (x,y) {
var b = this[x];
this[x] = this[y];
this[y] = b;
return this;
}
它可以被称为:
list.swap( x, y )
这是一种既避免内存泄漏又避免DRY的干净方法。
使用ES6可以这样做…
假设你有这两个数组……
const a = ["a", "b", "c", "d", "e"];
const b = [5, 4, 3, 2, 1];
你想交换第一个值:
const [a0] = a;
a[0] = b[0];
b[0] = a0;
和值:
a; //[5, "b", "c", "d", "e"]
b; //["a", 4, 3, 2, 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");