如何使用lodash库在JavaScript中交换数组元素的位置? 类似这样:
_.swap(array, fromIndex, toIndex) //but this is not working
这是在线 Lodash 测试器的链接,我在那里测试了一些方法,但没有一个起作用。
非常感谢您的任何帮助。谢谢!
如何使用lodash库在JavaScript中交换数组元素的位置? 类似这样:
_.swap(array, fromIndex, toIndex) //but this is not working
这是在线 Lodash 测试器的链接,我在那里测试了一些方法,但没有一个起作用。
非常感谢您的任何帮助。谢谢!
如果你只想要交换一个数组中两个元素的索引位置,你可以使用原生JavaScript很快地实现它。以下是使用现代ES6+语法的解决方案:
const swapArrayLocs = (arr, index1, index2) => {
[arr[index1], arr[index2]] = [arr[index2], arr[index1]]
}
如果您从未见过像我上面使用的解构赋值,您可以在这里阅读有关它的信息。当您需要交换两个变量的值(或在这种情况下,两个数组索引)时,这是一种特别有用的技术。
如果您需要支持像Internet Explorer这样的旧浏览器,这里有一个ES5-版本,语法上略微冗长:
var swapArrayLocs = function (arr, index1, index2) {
var temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
您还可以使用函数声明(而不是上面的函数表达式和箭头函数),使用任一方法:
function swapArrayLocs(arr, index1, index2) {
var temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
实现您所需功能的所有方法都将以相同方式使用 - 就像任何其他函数调用一样。 您将调用该函数,然后传递要影响的数组以及要交换其值的两个数组索引。
const myArray = ["a", "b", "c", "d", "e", "f"];
swapArrayLocs(myArray, 0, 4);
// myArray is now: ["e", "b", "c", "d", "a", "f"]
这将会操作数组,但是我所编写的函数并不返回任何东西。如果你希望改变这个情况,可以在末尾添加一个返回语句来返回 arr
或者可能包含两个被交换元素的数组...无论对于你的特定用例需要什么。
由于Array.splice返回一个新数组,包含被移除的值,因此你可以这样写:
const swapArrayLoc = (arr, from, to) => {
arr.splice(from, 1, arr.splice(to, 1, arr[from])[0])
}
使用临时变量。
const swapArrayLoc = (arr, from, to) => {
let temp = arr[to];
arr[to] = arr[from];
arr[from] = temp;
}
如果你想要获取完整的数组结果...
const swapElementPosition = (arr: any[], indexFrom: number, indexTo: number) => {
const swappedIndices = [arr[indexFrom], arr[indexTo]] = [arr[indexTo], arr[indexFrom]]
arr.forEach((aV, aVIndex) => {
if (swappedIndices.indexOf(aV) === -1) {
swappedIndices[aVIndex] = aV;
}
})
return swappedIndices.filter((sI) => sI != null);
}
const a = new Date().toLocaleDateString().split('/').reverse();
const b = [12, 13, 14, 15, 16];
const aa = swapElementPosition(a, 2, 3);
const bb = swapElementPosition(b, 3, 4);
console.log(aa);
console.log(bb)