많은 데이터의 수를 하나의 변수로 순서대로 관리할 때
필요한 자료구조가 바로 '배열’이다 배열은 대괄호([]
)로 감싸져 있다
배열(Array)의 안에 있는 값을 요소(Element) 라고 부른다
const array = [2062.82, 2053.2, "부산", "광주", "제주도"];
배열 안에는 String, Number, Array 등 다양한 데이터 타입 모두 입력 할 수있다
(,)로 구분하며 순서는 1이 아니라 0부터 시작한다
array[0] // 2062.82
변수명[index] 로 index 순서대로 접근하면 해당 요소를 가져올 수 있다
따로 설명이 필요없는 데이터를 담는다는 것으로 사용 되고 있다는 점이 object와 다른점이다
function modifyArray() {
const arrayNum = [20,30,40];
arrayNum[1] = 72;
return arrayNum;
}
console.log(modifyArray()) //20,72,40
arrayNum의 index[1]번째인 요소 30을 -> 72로 할당하였다
이렇듯 원하는 순서인 요소를 수정할 수 있다
push()
: 메서드는 배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환한다
const daysOfWeek = ["mon","tue","wed","thu","fri","sat"];
daysOfWeek.push("sun");
console.log(daysOfWeek); // ["mon","tue","wed","thu","fri","sat", "sun"]
.pop()
: 메소드는 배열의 마지막 요소를 제거하며 제거된 요소를 반환된다
const numberArr = [1, 4, 6];
const oneDown = threeArr.pop();
console.log(oneDown); // 6
console.log(numberArr); // [1, 4]
splice
: 메서드는 배열 내의 특정한 요소를 삭제하거나,
다른 요소로 대치하거나 새로운 요소를 추가할 때 사용된다
const num = [1, 2, 3, 4, 5];
num.splice(2, 1, 10);
console.log(num); // [ 1, 2, 10, 4, 5 ]
splice() 인자의 의미는 이렇다
slice
: 메서드는 배열 내의 특정한 요소의 index 범위에 따라 새로운 배열을 리턴한다
splice 메서드와는 다르게 slice 메서드는 원본 배열을 변형시키지 않는다
그렇기 때문에 이 메서드를 사용할 때는 slice 메서드를 적용한 새로운 변수를 선언해주어야 한다
slice 메서드는 필요에 따라 인자를 최소 1개만 쓸 수도 있다
const nums = [1, 2, 3, 4, 5];
const nums_new = nums.slice(1,4);
console.log(nums) // [ 1, 2, 3, 4, 5 ]
console.log(nums_new) // [ 2, 3, 4 ]
slice() 인자의 의미는 이렇다
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]
forEach
: 배열의 각 요소에 대해 주어진 함수를 실행한다, 함수는 인자로 배열 요소, 인덱스를 받는다. 배열 요소를 순환하며 해당 요소를 함수로 전달 -> 각 요소 실행
const rainbow = ['blue', 'pink', 'red', 'orange'];
const newColor = [];
rainbow.forEach(function (item) {
newColor.push('🌈' + item + '🌈');
});
console.log(newColor) //["🌈blue🌈","🌈pink🌈","🌈red🌈","🌈orange🌈"]
forEach
: 배열의 각 요소에 주어진 함수를 실행 -> 새로운 배열을 반환한다
첫번째 인자는 배열의 각 요소를 처리할 함수 ,
두번째 인자는 요소의 인덱스를 전달
const arr = [1, 2, 3];
const newArr = arr.map(function(item, index) {
console.log(item, index) // 1,0 / 2,1 / 3,2
return item * index;
});
console.log(newArr); // [0,2,6]
배열안에 객체에서 데이터를 뽑아보자
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);
ages //(3) [28, 37, 39]
const indexs = data.map((e) => e.index)
indexs // (3) [0, 1, 2]
const names = data.map((i) => i.name)
names // (3) ['Annette Middleton', 'Kidd Roman', 'Best Ratliff']
filter
: 기존 배열에서 조건을 만족하는 요소만 추출하여 새로운 배열을 만든다.
(특정 숫자나 날짜 정보를 추출할 때 유용하다)
const num = [1,2,3,4,5,6,7,8,9,10];
const result = num.filter((i) => {
return i % 2 === 1;
})
result // [1, 3, 5, 7, 9]