[英]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.