配列をクローン.js
色んな方法があるが、どれも一長一短
シャローコピー
code:script.js
const newArray = array.slice();
console.log(newArray4 === array4); // Expected Log Output : <Boolean> true code:script.js
const newArray = array.concat([]);
console.log(newArray4 === array4); // Expected Log Output : <Boolean> true code:script.js
console.log(newArray4 === array4); // Expected Log Output : <Boolean> true code:script.js
const newArray = Array.from(array);
console.log(newArray4 === array4); // Expected Log Output : <Boolean> true code:script.js
const newArray = array.map(n => n);
console.log(newArray4 === array4); // Expected Log Output : <Boolean> true code:script.js
const newArray = array.filter(n => true);
console.log(newArray4 === array4); // Expected Log Output : <Boolean> true ディープコピー
code:script.js
const newArray = JSON.parse(JSON.stringify(array));
console.log(newArray4 === array4); // Expected Log Output : <Boolean> false すべてをうまくコピーできるとは限らない
code:script.js
const newArray = globalThis.structuredClone(array);
console.log(newArray4 === array4); // Expected Log Output : <Boolean> false HTML DOM API / Baseline 2022
すべてをうまくコピーできるとは限らない
循環参照があってもうまいことやってくれるらしい