[])을 사용하며, 요소들은 쉼표로 구분const arr = [];
const arr2 = [1, 2, 3];const arr3 = new Array(1, 2, 3); // [1, 2, 3]
const arr4 = new Array(5); // [ <5 empty items> ]const arr = [1, 2, 3];
// 배열 안의 원소에 접근하기 위해서는 인덱스 번호를 이용합니다.
console.log(arr[0]); // 1
console.log(arr[1]); // 2
console.log(arr[2]); // 3
console.log(arr[3]); // ??arr[2] = 4; // [1, 2, 4]
arr[5] = 10; // [1, 2, 4, empty x 2, 10]const arr2 = [
[1, 2],
[3, 4],
[5, 6]
];
console.log(arr[0][0]);
console.log(arr[2][1]);push()와 pop()
push()는 배열의 끝에 요소를 추가하고 길이를 반환,
pop()는 배열의 마지막 요소를 제거하고 해당 요소를 반환.
const arr = [1, 2, 3];
arr.push(4, 5);
console.log(arr); // [1, 2, 3, 4, 5]
arr.pop();
console.log(arr); // [1, 2, 3, 4]
unshift()와 shift()
unshift()는 배열의 첫 번째 요소로 새로운 요소를 추가.
shift()는 배열에서 첫 번째 요소를 제거하고 반환.
const arr2 = ["사과", "바나나", "수박"]; arr2.unshift("오이", "배"); console.log(arr2); // ['오이', '배', '사과', '바나나', '수박']
arr2.shift();
console.log(arr2); // ['배', '사과', '바나나', '수박']
배열의 요소를 추가, 제거 또는 교체.
첫 번째 인자로 변경을 시작할 인덱스를, 두 번째 인자로는 변경할 요소의 개수를 전달. 추가할 요소가 있다면 추가할 요소를 쉼표로 구분하여 인자로 전달.
const arr3 = [1, 2, 3]; arr3.splice(1, 0, 4); //인덱스 1부터 시작하여 아무 요소도 제거하지 않고, 숫자 4를 추가 console.log(arr3); // [1, 4, 2, 3]arr3.splice(2, 1, 5, 6); //인덱스 2부터 시작하여 1개의 요소를 제거하고, 숫자 5와 6을 추가
console.log(arr3); // [1, 4, 5, 6, 3]
arr3.splice(0, 2); //인덱스 0부터 시작하여 2개의 요소를 제거
console.log(arr3);// [5, 6, 3]
slice()
const fruits = ["사과", "바나나", "체리", "블루베리", "두리안"];
console.log(fruits.slice(1, 4)); //["바나나", "체리", "블루베리"] (인덱스 1부터 인덱스 3까지(인덱스 4는 포함하지 않음))
console.log(fruits.slice(2, 10)); //["체리", "블루베리", "두리안"] (인덱스 2부터 인덱스 9까지(인덱스 10은 배열의 길이를 초과하므로 무시됨))
console.log(fruits.slice()); //["사과", "바나나", "체리", "블루베리", "두리안"] (매개변수 없이 slice()를 호출하면 배열의 전체 복사본을 만들어 반환)
console.log(fruits); //["사과", "바나나", "체리", "블루베리", "두리안"] (원본 배열을 변경하지 않고 새로운 배열을 반환)
sort()
배열을 변경하며, 정렬된 배열을 반환.
const fruits = ["사과", "바나나", "수박", "딸기", "포도"];
console.log(fruits.sort()); // ["딸기", "바나나", "사과", "수박", "포도"]
const nums = [3, 1, 8, 6]; console.log(nums.sort()); // [1, 3, 6, 8]
const nums2 = [23, 5, 1000, 42];
console.log(nums2.sort()); //[1000, 23, 42, 5]
//(숫자 1000, 23, 42, 5를 문자열로 변환한 후 유니코드 순서대로 정렬)
a - b 형태의 비교 함수를 사용하여 오름차순 정렬
const num3 = [13, 9, 10];num3.sort(function (a, b) {
console.log('a: ' + a, 'b: ' + b);
return a - b;
});
/
"a: 9"
"b: 13" // a - b는 음수임으로 a를 앞으로 => [9, 13**, 10]"a: 10"
"b: 9" // a - b는 양수임으로 b를 앞으로 => [9, 13, 10]"a: 10"
"b: 13" // a - b는 음수임으로 a를 앞으로 => [9, 10, 13]
"a: 10"
"b: 9" // a - b 는 양수임으로 b를 앞으로 => [9, 10, 13]
*/
indexOf
요소의 첫 번째 인덱스를 반환. 요소가 배열에 없으면 -1을 반환.
const arr = [1, 2, 3, 1, 2, 3, 4]
arr.indexOf(2); // 1 (숫자 2는 인덱스 1)
arr.indexOf(5); // -1 (해당 요소가 배열에 없을 때는 -1을 반환)
includes
요소가 포함이 되어 있으면 true 아니면 false를 반환.
const arr1 = ['hello', 'world', 'hojun'] arr1.includes('world') //trueconst arr1 = ['hello', 'world', 'hojun']
arr1.includes('leehojun') //false
const arr1 = ['hello', 'world', 'hojun']
arr1.includes('jun') //true
forEach()
배열의 요소를 순환하면서 해당 요소를 함수로 전달하고, 이 함수가 각 요소에 대해 실행. 각 요소와 인덱스를 출력
const arr = ['참외', '키위', '감귤']; arr.forEach(function(item, index) { //item으로 받고,인덱스를 index로 받 console.log(item, index); arr[index] = index; });
// 결과
// 참외 0
// 키위 1
// 감귤 2
const avengers = ['spiderman', 'ironman', 'hulk', 'thor'];
const newAvengers = [];
avengers.forEach(function (item) {
newAvengers.push('💖' + item + '💖');
});
// ["💖spiderman💖","💖ironman💖","💖hulk💖","💖thor💖"]
map()
배열의 각 요소에 대해 주어진 함수를 실행하고, 그 결과를 새로운 배열로 반환.
첫 번째 인자로는 배열의 각 요소를 처리할 함수를, 두번째는 요소의 인덱스를 전달.
const arr = [1, 2, 3]; const newArr = arr.map(function(item, index) { return item * index; // 각 요소 item과 그 인덱스 index를 곱한 값 });
console.log(newArr); // [0, 2, 6] , ((10),(21),(3*2))
💡 forEach()와 map()은 별로 다르지 않아보여요!
forEach()와 map()은 둘 다 배열의 각 요소에 대해 주어진 함수를 실행합니다. 하지만 forEach 메서드의 경우 반환값이 없지만 map 메서드는 새로운 배열을 반환한다는 차이.
배열 안에 객체에서 데이터를 뽑는 형태로도 사용.
const data = [ { "_id": "642ba3980785cecff3f39a8d", "index": 0, "age": 28, "eyeColor": "green", "name": "Annette Middleton", "gender": "female", "company": "KINETICA" }, { "_id": "642ba398d0fed6e17f2f50c9", "index": 1, "age": 37, "eyeColor": "green", "name": "Kidd Roman", "gender": "male", "company": "AUSTECH" }, { "_id": "642ba39827d809511d00dd8d", "index": 2, "age": 39, "eyeColor": "brown", "name": "Best Ratliff", "gender": "male", "company": "PRISMATIC" } ];
const ages = data.map((item) => item.age);
filter()
기존의 배열에서 특정 조건을 만족하는 요소들만 추출하여 새로운 배열을 만.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const newArr = arr.filter(function(el) { return el % 2 === 0; //나머지를 구해서 짝수인지 확인 });
console.log(newArr); // [2, 4, 6, 8, 10]
const arr11 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const newArr = arr11.filter(el => el % 2 === 0);
console.log(newArr); // [2, 4, 6, 8, 10]
reduce
배열의 요소를 모두 더하고자 할 때 사용.
이전 계산 결과인 a(accumulator, 누적값)와 현재 요소인 c(currentValue)를 함수의 인자로 전달.
초기값을 생략하면 a는 첫번째 요소를 사용하며, c는 두번째 요소(1번 인덱스) 요소 부터 순회.
빈 배열에서 초기값 없이 reudce()를 호출하면 오류가 발생. 초기값을 0으로 설정해두는 편이 안전.
const arr1 = [1, 2, 3, 4, 5] let result = arr1.reduce((a, c) => { console.log(`a: ${a}, c:${c}`); return a + c; }, 0) console.log(result);const arr2 = []
arr2.reduce((a, c) => a + c) // errorconst arr3 = [1]
arr3.reduce((a, c) => a + c)// 뒤에서 배울 객체 연산도 됩니다.
const data = [
{
"_id": "642ba3980785cecff3f39a8d",
"index": 0,
"age": 28,
"name": "Annette Middleton",
},
{
"_id": "642ba398d0fed6e17f2f50c9",
"index": 1,
"age": 37,
"name": "Kidd Roman",
},
{
"_id": "642ba39827d809511d00dd8d",
"index": 2,
"age": 39,
"name": "Best Ratliff",
}
];const ageSum = data.reduce((a, c) => a + c.age, 0);
console.log(ageSum); // 104
join
배열의 요소들을 연결할 때 사용. 인자로 문자열을 전달하여 연결 문자로 사용.
const arr1 = ['hello', 'world', 'hojun'] arr1.join('!') // hello!world!hojunconst arr2 = ['010', '1034', '1100']
arr2.join('-') // 010-1034-1100const arr3 = [010, 1034, 1100]
arr3.join('-') // 이렇게 하시면 안됩니다. 0으로 시작하는 숫자를 8진수로 인식합니다.
// 0b100 // b는 바이너리의 첫글자입니다.
// 0o100 // o는 옥타의 첫글자입니다.
// 0x100 // x는 헥사를 표현합니다.
concat
여러 개의 배열을 연결하거나 배열을 복사할 때 사용.
기존 배열의 수정 없이 새로운 배열을 반환.
인자 없이 concat 메서드를 실행하면 얕은 복사.
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const arr3 = [7, 8];arr1.concat(arr2, arr3);
const copy = arr1.concat();
copy[0] = 0;
console.log(copy); // [0, 2, 3]
console.log(arr1); // [1, 2, 3]
🧐 데이터를 이어 붙일 때에는 뒤에서 배울 전개 구문을 사용하기도 합니다.
const a = [1, 2, 3];
const b = [4, 5, 6];
const c = [8]
const result = [**...a**, **...b**, 7, **...c**];
// 더하기 연산자를 사용하면 배열을 문자열로 변환하여 연결합니다
[10] + [10] // 1010입니다!