JS에서의 배열은 배열을 흉내낸 객체!
const numArray = [1,2,3,4];
console.log(typeof numArray); // object -> 객체라는 답변이 나옴
배열의 길이
//배열의 길이를 알아내는 명령어
배열이름.length;
JS에서 배열의 길이와 배열의 요소 개수는 같은 말인가…?
→ No : 아닐 수 있음
const arr = [];
arr[2] = 3;
console.log(arr.length); // 3
console.log(arr); //[ <2 empty items>, 3 ]
empty가 들어감결론 : JS에서 배열의 길이와 배열의 사용자가 초기화 해준 요소 개수는 다를 수 있으며 사용자가 초기화 해주지 않은 요소는 empty라는 값을 가지게 된다.
배열에 요소 추가하기
배열을 직접 건드리는 방식
→ 원본 배열을 직접 건드리는 방식이다.
배열이름.push(추가요소)
배열을 직접 건드리지 않는 방식
→ concat을 활용하고자 한다면 변수에 담은 다음 활용을 해야한다.
배열이름.concat(추가요소)
//활용하려면
const 변수이름 = 배열이름.concat(배열추가요소);
배열의 요소 빼내기(제거하기)
맨 마지막 인덱스 제거하기
배열이름.pop();
배열 순회하기
기존의 방법 → 비효율적… (접근 할때마다 for문을 작성해줘야해…? 너무 힘든데..)
const nameArr = ['민철','영수','영희','민수'];
for(var i=0; i<nameArr.length;i++){
console.log(`내 이름은 ${nameArr[i]}야`);
}
forEach 로 배열 순회 하기
순회하려는배열.forEach(함수로 정의한 순회하면서 하는 일);
순회하려는배열.forEach -> 인자마다 돌린다 라는 뜻
배열의 값을 가져오려면
순회하려는배열.forEach(function(인자값){
console.log(`순회하는 값 번호 : ${인자값}`);
}
)
//예시
const numArray = [1,2,3,4];
numArray.forEach(function(num){
console.log(num);
})
화살표 함수로 더 간단하게 작성하기
nameArr.forEach(name=>console.log(`내 이름은 ${name}야`));
map 으로 배열 순회하기
→ 처리한 결과를 바탕으로 새로운 배열을 return 해준다
순회하려는배열.map(함수로 정의한 순회하면서 할 일);
oddArr.map(num=>{console.log(num*2)});
const newArr = oddArr.map(num=>num*2);
console.log(newArr);
forEach vs map
return받으나 forEach는 그러지 않음.배열에 원하는 요소만 사용하기 : 필터링
filter : 특정 조건을 만족하는 요소들만 가지고 새로운 배열을 만들어주는 함수
원본배열.filter(함수로 정의 된 필터링 작업);
예시)
const oddArr = [1,3,5,7,9];
const newArr = oddArr.filter(name => name>5);
console.log(newArr);
//이런느낌
const newArr = oddArr.filter(function 함수이름(name){
if(name>5){
newArr.push(name);
}
})
예시)
const postlist =[{"date":"yesterday","id":1},{"date":"yesterday","id":2},{"date":"today","id":3}]
const yesterdaypost = postlist.filter(post=>post.date ==="yesterday");
console.log(yesterdaypost);
const idUp = postlist.filter(post=>post.id >=2);
console.log(idUp);