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