[英]How can I make two JS Splice work together
我有两种拼接方法可以按预期工作,但前提是我一次有一个
const prev = [
[135,136,137,138,139],
[275,276,277,278,279],
];
const after = [
[141,142,143,144,145],
[281,282,283,284,285],
];
scrollFrom.splice(0, 0, 135,136,137,138,139);
我得到:
[135, 136, 137, 138, 139, 140 ...]
如果我只有:
(...)
scrollFrom.splice(1, 0, ...after[0]);
我会得到:
[140, 141, 142, 143, 144, 145 ...]
但是,如果我有两个拼接功能,像这样:
(...)
scrollFrom.splice(0, 0, ...prev[0]);
scrollFrom.splice(1, 0, ...after[0]);
结果是这样的:
[135, 141, 142, 143, 144, 145, 136, 137, 138, 139, 140 ... ]
我想获得的是:
[135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145 ... ]
你能帮我弄清楚我做错了什么或其他解决方案吗? 提前致谢。
我认为问题在于您不允许插入已插入的项目。 您将索引 1 用于第二个splice
,但prev
有多个条目。 插入:
scrollFrom.splice(0, 0, ...prev[0]);
scrollFrom.splice(prev[0].length, 0, ...after[0]);
// −−−−−−−−−−−−−−−^^^^^^^^^^^^^^
现场示例:
const prev = [ [135,136,137,138,139], [275,276,277,278,279], ]; const after = [ [141,142,143,144,145], [281,282,283,284,285], ]; const scrollFrom = []; // Or whatever scrollFrom.splice(0, 0, ...prev[0]); scrollFrom.splice(prev[0].length, 0, ...after[0]); // −−−−−−−−−−−−−−−^^^^^^^^^^^^^^ console.log(scrollFrom);
.as-console-wrapper { max-height: 100% !important; }
我没有考虑到数组的索引随着第一个拼接而增加,呃!
scrollFrom.splice(0, 0, ...prev[0]);
scrollFrom.splice(6, 0, ...after[0]);
这将返回: [135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, ...]
完美!
感谢您的回复。
调用第二个splice
,您应该考虑使用第一个splice
插入的项目。 因此,您应该从最后一个元素之后拼接,而不是从1
拼接:
let initialLength = scrollFrom.length; // cache the initial length of 'scrollFrom' in case it is not equal to 1 (contains 0 or more than 1 elements)
scrollFrom.splice(0, 0, ...prev[0]); // insert elements from `prev[0]` at the begining of the array
scrollFrom.splice(prev[0].length + initialLength, 0, ...after[0]); // insert elements from `after[0]` at the "new end" which is after the newly added elements and the already existing elements
或者更好的是,使用unshift
插入prev[0]
元素并push
插入after[0]
元素,如下所示:
scrollFrom.unshift(...prev[0]);
scrollFrom.push(...after[0]);
unshift
将在已经存在的scrollFrom
元素之前插入新元素,而push
将在之后插入它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.