변수의 종류중 하나로, 배열에는 다양한 값을 저장할 수 있다.
[] 안에 값을 넣어 선언을 할 수 있으며,
animals[] 안에 인덱스를 넣어 해당 부분에 접근할 수 있다.const animals = ["rabbit","turtle","giraffe"]; console.log(animals[0]); // rabbit
배열은 참조 값을 저장하기 때문에 다음과 같이 얕은 복사로 할당할 경우
animals2의 값을 바꾸면 animals의 값도 바뀌는 문제가 생길 수 있다.const animals2 = animals; animals2[0] = "cat"; console.log(animals); // ["cat", "turtle", "giraffe"] console.log(animals2); // ["cat", "turtle", "giraffe"]
따라서 전개 연산자(...)를 사용해 깊은 복사를 한다면 이를 해결할 수 있다.
const animals2 = [...animals]; animals2[0] = "cat"; console.log(animals); // ["rabbit", "turtle", "giraffe"] console.log(animals2); // ["cat", "turtle", "giraffe"]
배열은 typeof를 사용할 경우 "object"라 나온다.
그렇기 때문에 object만을 입력받아야 하는 조건을 만들땐, Array.isArray()를 사용하면 된다.
array 타입이 맞을경우 true, 아니면 false를 반환한다.console.log(Array.isArray(animals)); // true
배열 내의 모든 요소 각각에 주어진 함수를 호출한다.
animals.forEach((item,index)=>{ console.log(item,index); }) // rabbit 0 // turtle 1...
배열 내의 모든 요소 각각에 주어진 함수를 호출, 새로운 배열을 반환한다.
foeEach와 마찬가지로 (item,index,array)를 받아올 수 있다.const animals = ["rabbit","turtle","giraffe"]; const animals2 = animals.map(item => item); // ["rabbit","turtle","giraffe"]
animals.push("cat"); // ["rabbit","turtle","giraffe","cat"]
animals.pop(); // ["rabbit","turtle","giraffe"]
animals.shift(); // ["turtle","giraffe"]
animals.unshift("rabbit"); // ["rabbit","turtle","giraffe"]
animals.indexOf("rabbit"); // 0
animals.splice(index,number,item1,item2...); // index = 0, number=1; // ["turtle","giraffe"]
여러개 제거하기
animals.splice(1,2); // ["rabbit"]
제거 후 교체
animals.splice(1,1,"cat"); // ["rabbit", "cat", "giraffe"]
const animalsCopy = animals.slice(); // slice(start,end) // ["rabbit","turtle","giraffe"]
인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환한다.
기존 배열을 변경하지 않고 새로운 배열을 반환한다.const animals = ["rabbit","turtle","giraffe"]; const animals2 = ["cat"]; const animalsConcat = animals.concat(animals2); // ["rabbit","turtle","giraffe","cat"]
기존 배열을 변경하지 않고 새로운 문자열을 반환한다.
const animals = ["rabbit","turtle","giraffe"]; const animalsJoin = animals.join("-"); // ()안에 구분할 문자를 넣는다. ("") 공백 없이 // "rabbit-turtle-giraffe"