admin管理员组

文章数量:1359218

Is there any way to make the splice() non-destructive?

What I need to do is to retain the arr2 as it is after I call the function.

function foo(arr1, arr2, n) {
   let result = arr2;
   result.splice(n, 0, ...arr1.slice(0, arr1.length));
   console.log(arr2);
}

foo(["I'm", "not", "done"], ["sorry", "yet"], 1);

Although it returns sorry,I'm,not,done,yet which is what I want but the elements of arr2 shouldn't change.

Is there any way to make the splice() non-destructive?

What I need to do is to retain the arr2 as it is after I call the function.

function foo(arr1, arr2, n) {
   let result = arr2;
   result.splice(n, 0, ...arr1.slice(0, arr1.length));
   console.log(arr2);
}

foo(["I'm", "not", "done"], ["sorry", "yet"], 1);

Although it returns sorry,I'm,not,done,yet which is what I want but the elements of arr2 shouldn't change.

Share Improve this question edited Jul 3, 2018 at 8:07 Vikasdeep Singh 21.8k16 gold badges82 silver badges106 bronze badges asked Jul 3, 2018 at 7:57 isemajisemaj 5871 gold badge6 silver badges21 bronze badges 1
  • 4 Use slice instead of splice. Same syntax, but not "destructive". – Seblor Commented Jul 3, 2018 at 7:57
Add a ment  | 

5 Answers 5

Reset to default 6

You can (shallow) copy the array before modifying it with .concat.

let result = [].concat(arr2);
// ... modify result...

You can use the "non destructive" function, AKA slice :
https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Here's a SO question with the difference between slice and splice : JavaScript Array splice vs slice

The syntax is the exact same, so you just have to remove one letter

function foo(arr1, arr2, n) {
   let result = arr2;
   result.slice(n, 0, ...arr1.slice(0, arr1.length));
   console.log(arr2);
}

foo(["I'm", "not", "done"], ["sorry", "yet"], 1);

Try this. Slice function without parameter makes a (shallow) copy of an array .

let result = arr2.slice();

Inside your function you can also use the spread operator (in case you are using ES2015) to create a copy of arr2:

let result = [...arr2];

Option 1:

You can use array.concat().

Please find below example:

function foo(arr1, arr2, n) {
  let result = [].concat(arr2);
  result.splice(n, 0, ...arr1.slice(0, arr1.length));
  console.log(arr2);
  console.log(result);
}

foo(["I'm", "not", "done"], ["sorry", "yet"], 1);

Option 2:

Using array.slice() mentioned in ment above by @Seblor like this let result = arr2.slice();

Example below:

function foo(arr1, arr2, n) {
  let result = arr2.slice();
  result.splice(n, 0, ...arr1.slice(0, arr1.length));
  console.log(arr2);
  console.log(result);
}

foo(["I'm", "not", "done"], ["sorry", "yet"], 1);

本文标签: Make nondestructive the splice of JavaScriptStack Overflow