有没有一种更简单的方法来交换数组中的两个元素?
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;
function swapRandomValues(arr, numValues) {
if (numValues > arr.length / 2) {
console.log("Cannot swap more than half of the array.");
return;
}
for (let i = 0; i < numValues; i++) {
let randomIndex1 = Math.floor(Math.random() * arr.length);
let randomIndex2 = Math.floor(Math.random() * arr.length);
[arr[randomIndex1],arr[randomIndex2]] = [arr[randomIndex2],arr[randomIndex2]]
}
console.log(arr);
}
let arr = [1,2,3,4,5,6,7,8,9,10,11,12];
swapRandomValues(arr, 6);
仅仅为了好玩,另一种不使用任何额外变量的方法是:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// swap index 0 and 2
arr[arr.length] = arr[0]; // copy idx1 to the end of the array
arr[0] = arr[2]; // copy idx2 to idx1
arr[2] = arr[arr.length-1]; // copy idx1 to idx2
arr.length--; // remove idx1 (was added to the end of the array)
console.log( arr ); // -> [3, 2, 1, 4, 5, 6, 7, 8, 9]
尝试这个函数...
$(document).ready(function () {
var pair = [];
var destinationarray = ['AAA','BBB','CCC'];
var cityItems = getCityList(destinationarray);
for (var i = 0; i < cityItems.length; i++) {
pair = [];
var ending_point = "";
for (var j = 0; j < cityItems[i].length; j++) {
pair.push(cityItems[i][j]);
}
alert(pair);
console.log(pair)
}
});
function getCityList(inputArray) {
var Util = function () {
};
Util.getPermuts = function (array, start, output) {
if (start >= array.length) {
var arr = array.slice(0);
output.push(arr);
} else {
var i;
for (i = start; i < array.length; ++i) {
Util.swap(array, start, i);
Util.getPermuts(array, start + 1, output);
Util.swap(array, start, i);
}
}
}
Util.getAllPossiblePermuts = function (array, output) {
Util.getPermuts(array, 0, output);
}
Util.swap = function (array, from, to) {
var tmp = array[from];
array[from] = array[to];
array[to] = tmp;
}
var output = [];
Util.getAllPossiblePermuts(inputArray, output);
return output;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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");
使用ES6,可以这样做...
想象一下你有这2个数组...
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]
array.unshift( array.pop() );
[1, 2, 3] => [3, 1, 2]
而不是 [1, 2, 3] => [3, 2, 1]
。 - David Archibald
with()
可以在一行中完成:list.with(x,list[y]).with(y,list[x])
看看我的答案和示例! - XMehdi01with()
可以在一行中完成:list.with(x,list[y]).with(y,list[x])
看看我的回答,附带一个示例! - undefined