언어/자바스크립트
JavaScript concat
realtrynna
2022. 2. 21. 19:56
JavaScript concat
인자로 주어진 배열이나 값을 기존 배열과 합쳐 새 배열 return 기존 배열 변경하지 않음(얕은 복사)
- concat()
const array = ["로니콜먼", "브렌치워렌", "리치피아나", "숀클로리다"]
const copyArray = array.concat(array);
console.log(copyArray); // ['로니콜먼', '브렌치워렌', '리치피아나', '숀클로리다']
- 12가지 색 랜덤 셔플
const array = ["red", "orange", "yellow", "green", "pink", "black"];
const copyArray = array.concat(array);
let shuffle = [];
for (let i = 0; copyArray.length > 0; i++) {
const random = Math.floor(Math.random() * copyArray.length);
shuffle = shuffle.concat(copyArray.splice(random, 1));
}
console.log(shuffle);
[1].concat(2) // [1, 2]
[1].concat([2]) // [1, 2]