자바스크립트에서 배열을 자유자재로 다루기 위해 연습겸 정리해보려 한다.
배열 값 복사 방법
- 전개연산자(
[...arr]
), slice()
, concat()
const arr = [1, 2, 3, 4, 5];
arrRest = [...arr];
console.log(arrRest);
arr2 = [].concat(arr);
console.log(arr2);
arr3 = arr2.concat([...arr]);
console.log(arr3)
arr4 = arr.slice(2, 4);
console.log(arr4);
배열 생성
const fruit = [];
push()
fruit.push("apple", "banana", "melon");
console.log(fruit);
pop()
const fruit2 = fruit.pop();
console.log(fruit2);
console.log(fruit);
shift()
const fruit3 = fruit.shift();
console.log(fruit3);
console.log(fruit);
unshift()
fruit.unshift("orange", "cherry");
console.log(fruit);
concat()
- 하나 이상의 배열을 합쳐 새로운 배열을 반환.
const arrNum1 = [1, 2];
const arrNum2 = [3, 4];
const arrNum3 = arrNum1.concat(arrNum2);
const arrNum4 = arrNum2.concat(arrNum1);
console.log(arrNum3);
console.log(arrNum4);
slice()
- 시작지점에서 끝지점 전까지의 인덱스 결과물을 배열로 반환.
const arrSlice1 = [1, 2, 3, 4, 5];
const arrSlice2 = arrSlice1.slice(1,3);
console.log(arrSlice2);
splice()
- 시작지점에서부터 지우고 싶은 개수를 정하고 그 자리에 요소를 추가. 결과물은 배열로 반환
const arrSplice1 = [1, 2, 3, 4, 5];
const arrSplice2 = arrSplice1.splice(0, 2)
console.log(arrSplice1);
console.log(arrSplice2);
reverse()
const reverseArr = [1, 2, 3, 4, 5];
reverseArr.reverse();
console.log(reverseArr);
sort()
const sortArr = [2, 5, 12, 1, 6, 3];
sortArr.sort();
console.log(sortArr);
sortArr.sort((a, b) => a - b);
console.log(sortArr);
join()
- 배열 원소들을 빼내서 연결하여 하나의 문자열로 반환한다.
const joinArr1 = ["I", "AM", "A", "BOY"];
const joinArr2 = joinArr1.join("-");
const joinArr3 = joinArr1.join();
console.log(joinArr2);
console.log(joinArr3);
toString()
const numArr1 = [1,2,3,4,5]
const numArr2 = numArr1.toString();
console.log(numArr2);