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.
-
4
Use
slice
instead ofsplice
. Same syntax, but not "destructive". – Seblor Commented Jul 3, 2018 at 7:57
5 Answers
Reset to default 6You 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
版权声明:本文标题:Make non-destructive the splice of JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744081069a2587649.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论