for문과 배열

서지우·2023년 7월 18일
0

JavaScript

목록 보기
3/11

for문과 배열

for사용방법

for문의 사용방법은 아래의 실습의 주석으로 설명해놨다.

실습 - s04.html

<script>
    //for 사용방법
    
    // 자바스크립트 배열은
    // 자바의 배열과 ArrayList의 혼합느낌이다.
    // 타입이 다른 값이 들어갈 수 있다.
    // 길이가 가변적이다.
    // 메소드가 있다.
    const intArray = [10,20,30];

    // 기본 for
    for (let i = 0; i < intArray.length; i++) {
        const element = intArray[i];
        console.log(element); // 10 20 30
    }
    // for in - 배열이나 객체의 key 값을 사용한다.
    for (const i in intArray) {
       console.log(intArray[i]); // 10 20 30
    }
    const obj = {
        name:"홍길동",
        age:12
    }
    for (const key in obj) {
      console.log(key); // name age
      console.log(obj[key]); // name 홍길동 age 12 (위의 콘솔이랑 같이)
    }

    // for of 배열의 value를 사용한다
    for(const value of intArray){
        console.log(value); // 12 10 20 30
    }

    // foreach는 매개변수로 함수를 받는다
    intArray.forEach(function(value){
        console.log(value); //10 20 30
    });

    intArray.forEach((value) => console.log(value)); //10 20 30

    // 배열의 메소드
    // 리턴값이 없는 것이 특징
    intArray.forEach((value, index, array) => {
        console.log(value); // (3) [10, 20, 30] 20 1
        console.log(index); //(3) [10, 20, 30] 30 1
        console.log(array); //(3) [10, 20, 30]
    });
</script>

실행결과


배열

실습 - s08.html

주석으로 설명..

<script>
    const car = {
        엔진 : {
            기통 : 4,
            방식 : "직렬"
        },
        name : "아반떼",
        바퀴 : ["1번", "2번", "3번", "4번"], 
    } 

    // 배열 안의 객체
    const objArray = [
        {name:"홍길동", age:12},
        {name:"임꺽정", age:12}
    ];

    for (let i = 0; i < objArray.length; i++) {
        
        const el = objArray[i];
        console.log(el);
        console.log(el.name);
        
    }
</script>

실행결과


배열 forEach와 비슷한 메소드들

실습 - s09.html

실습으로 보면 된다!!

<script>
    // 배열의 forEach와 비슷한 메소드들

    const array = [
        {name:"홍길동", age:12},
        {name:"임꺽정", age:13}
    ];

    // 배열의 데이터를 반복하는데 결과값이 필요 없을 경우
    array.forEach((value, index, array) => {
        console.log(value);// {name: '홍길동', age: 12} {name: '임꺽정', age: 13}
    });

    // filter 배열의 데이터를 반복하는데
    // 조건의 맞는 요소만 걸러낼 때 사용
    // 함수를 매개변수를 받는데 (콜백함수) return값이 true나 false여야 한다.
    // 콜백함수의 return값이 true면 리스트에 남고 false면 필터링 된다
    // 나이가 13살 이상인 사람만 필터링 하는 함수
    const check = (value, index, array) => {
        return value.age > 12;
    }

    const result1 = array.filter(check);
    console.log("result1");
    console.log(result1); //0:{name: '임꺽정', age: 13}

    // map 배열의 데이터를 반복하는데
    // 기존의 데이터 형식을 다른 형식으로 변경할 때 사용
    // 함수 매개변수를 받는데 (콜백함수) return값이 어느 것이든 될 수 있다.
    // map은 객체 Map하고 전혀 상관이 없으니 주의
    // 기존의 객체 배열 -> 이름만 있는 문자열 배열로 전환
    const result2 = array.map((value, index, array) => {
        return value.name;
    });
    console.log("result2");
    console.log(result2); //(2) ['홍길동', '임꺽정']

    // 연습
    // forEach - name님 안녕하세요 반복출력
    // filter - 이름에 '길'자가 들어간 사람만 남기기
    // map - 나이만 뽑아서 숫자 배열 만들기
    
    // 매개변수 이름이 맘대로 바꿀 수 있음. 굳이 value로 안해도 됨.
    array.forEach((obj) => {
        console.log(obj.name + "님 안녕하세요");
    });
    // array.forEach((obj) => console.log(obj.name + "님 안녕하세요"));
    
    const result3 = array.filter((value) => {
        return value.name.includes("길");
    });
    // const result3 = array.filter((value) => value.name.includes("길"));
    console.log("result3");
    console.log(result3);

    const result4 = array.map((value) => {
        return value.age;
    });
    // const result4 = array.map((value) => value.age);
    console.log("result4");
    console.log(result4);

</script>

실행결과


전개 연산자

실습 - s07.html

<script>
    // 전개 연산자
    // 배열이나 객체의 요소를 뿌린다

    const intArray = [10,20,30];
    
    const secondArray = [...intArray, 40];
    console.log(secondArray); //(4) [10, 20, 30, 40]

    const obj = {
        name: "홍길동",
        age: 12,
    }

    const secondObj = {...obj, hobby : "야구"}
    console.log(secondObj); //{name: '홍길동', age: 12, hobby: '야구'}

    // 덮어씌어진다
    const thirdObj = {...obj, age : 20}
    console.log(thirdObj); //{name: '홍길동', age: 20}

    const { name, ...remainObj } = secondObj;
    console.log(remainObj); //{age: 12, hobby: '야구'}
</script>

실행결과


구조 분해 할당

객체와 배열은 자바스크립트에서 가장 많이 쓰이는 자료 구조

키를 가진 데이터 여러 개를 하나의 엔티티에 저장할 땐 객체를, 컬렉션에 데이터를 순서대로 저장할 땐 배열을 사용한다.

개발을 하다 보면 함수에 객체나 배열을 전달해야 하는 경우가 생기곤 한다.

이럴 때 객체나 배열을 변수로 '분해’할 수 있게 해주는 특별한 문법인 구조 분해 할당(destructuring assignment) 을 사용할 수 있다.

함수의 매개변수가 많거나 매개변수 기본값이 필요한 경우 등에서 구조 분해(destructuring)는 그 진가를 발휘한다.

실습 - s06.html

실습 파일의 주석으로 보면 됨.

<script>
    // 구조 분해 할당

    const intArray = [10, 20, 30];
    // const first = intArray[0];
    // const second = intArray[1];

    // 순서가 중요해서
    // 0번째부터 변수가 할당된다
    // 2번째 것을 가져오려면 0번째 1번째 것도 가져와아 함

    const[first,second,asdf]=intArray;
    console.log(first); // 10
    console.log(second); // 20
    console.log(asdf); // 30

    const obj = {
        name : "홍길동",
        age : 12,
    };
    // 객체를 구조 분해 할당할 때에는 이름이 중요하다
    const {age, name} = obj;
    console.log(age); // 12
    console.log(name); // 홍길동

</script>

profile
미래가 기대되는 풀스택개발자 공부 이야기~~

2개의 댓글

comment-user-thumbnail
2023년 7월 18일

정보가 많아서 도움이 많이 됐습니다.

답글 달기
comment-user-thumbnail
2023년 7월 18일

유익한 글 잘 봤습니다, 감사합니다.

답글 달기