JSFiddle - React, Tailwind, and code Playground
by ken3desu
HTML
<h5>素朴な splice メソッドの使い方による挿入結果</h5>
<pre id="destroy-a"></pre>
<h5>スプレッド演算子を使用した挿入結果</h5>
<pre id="spread-b"></pre>
<h5>非破壊挿入結果</h5>
<div id="not-destroy-a">
<pre class="a">a: <span></span></pre>
<pre class="c">c: <span></span></pre>
</div>
JavaScript
// 初期データ生成
const createInitData = () => {
const a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const b = ['d', 'e', 'f'];
return {a, b};
};
/** splice メソッドによる配列の中間へ配列を挿入する方法 */
const destroyA = () => {
const {a, b} = createInitData();
a.splice(3, b.length, b[0], b[1], b[2]);
document.getElementById('destroy-a').innerText = JSON.stringify(a);
};
/** スプレッド演算子による展開を使った楽な挿入方法 */
const spreadB = () => {
const {a, b} = createInitData();
a.splice(3, b.length, ...b);// 引数中でスプレッド演算子で展開すると複数の引数と化します
document.getElementById('spread-b').innerText = JSON.stringify(a);
};
/** スプレッド演算子を使った非破壊挿入方法 */
const notDestroyA = () => {
const {a, b} = createInitData();
(c = [...a]).splice(3, b.length, ...b);// [...配列]とすることで配列をクローンできます(配列中の要素までクローンするディープクローンでないことに注意)。
document.querySelector('#not-destroy-a > .c > span').innerText = JSON.stringify(c);
document.querySelector('#not-destroy-a > .a > span').innerText = JSON.stringify(a);
};
window.onload = () => {
destroyA();
spreadB();
notDestroyA();
};