[英]copy arr1 to arr 2 at given index n and arr 1 and arr2 should be same after function runs
I am trying to copy arr1 to arr 2 at given index n and arr 1 and arr2 should be same after function runs.我正在尝试在给定索引 n 处将 arr1 复制到 arr 2,并且在 function 运行后 arr 1 和 arr2 应该相同。 So I have put a = arr2 and operate on a but arr2 is also changing所以我放了 a = arr2 并对 a 进行操作,但 arr2 也在变化
function frankenSplice(arr1, arr2, n) { let a = arr2 console.log(a) a.splice(n,0,...arr1); console.log(arr2) return a } console.log(frankenSplice([1, 2, 3], [4, 5, 6], 1));
Arrays in javascript are mutable, so when you use javascript 中的 Arrays 是可变的,所以当你使用
let a = arr2
array a
becomes arr2
, and when you modify one, you modify both (beacuse they are essentialy the same array)数组a
变为arr2
,当你修改一个时,你同时修改了两个(因为它们本质上是同一个数组)
To solve your problem, you can use spread operator to copy content of your original array to the new one, so it would look like this为了解决您的问题,您可以使用扩展运算符将原始数组的内容复制到新数组,所以它看起来像这样
let a = [...arr2]
You need to make a
a copy of arr2
, one way to do that would be to use slice :您需要制作arr2
a
副本,一种方法是使用slice :
const frankenSplice = (arr1, arr2, n) => { const a = arr2.slice(0); // 0 is not required but makes it slightly faster a.splice(n, 0, ...arr1); return a } const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; console.log(frankenSplice(arr1, arr2, 1)); console.log(arr1); console.log(arr2);
Using flatMap
should make simplify for this case.使用flatMap
应该可以简化这种情况。
function frankenSplice(arr1, arr2, n) { return arr2.flatMap((num, i) => (i === n? [...arr1, num]: num)); } console.log(frankenSplice([1, 2, 3], [4, 5, 6], 1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.