在React组件中的ES2015非变异阵列交换(或磁通动作)

D D*_*ham 4 javascript immutability reactjs

也许我一直在搜索错误的关键字,但我一直试图找到一个JavaScript(最好是ES2015 +)函数的例子来以非变异(不可变)的方式交换两个数组值.我也想使用纯JS来做这个,而不必添加不变量库.

例如,如果我有[1, 2, 3, 4, 5, 6],我想将3和4(或可能是它们的索引)传递给返回新数组的函数[1, 2, 4, 3, 5, 6].我发现了一些方法,但他们通过直接替换值来改变数组.我需要一种不可改变的方式.我猜也许用切片?我这样做是一个React组件,如果这很重要,并且数组是一个状态值.

TIA!

Bor*_*nte 6

不是ES6(还在学习它)

function swap(array, first, second){
  var final = array.slice();
  temp = final[first];
  final[first] = final[second];
  final[second] = temp;
  return final
}
Run Code Online (Sandbox Code Playgroud)

ES6感谢@Benjamin

const swapIndices = (array,index1,index2) => { 
  const newArray = array.slice(); 
  newArray[index1] = array[index2]; 
  newArray[index2] = array[index1]; 
  return newArray; 
}
Run Code Online (Sandbox Code Playgroud)