String, Boolean, Object

minkyeongJ·2022년 5월 2일
0

코드라이언FE

목록 보기
21/23
post-thumbnail

1. String(문자열)

텍스트를 나타내는데 사용

1.1 표기법

        // 작은 따옴표('')
        var string1 = '문자열';
        // 큰따옴표("")
        var string2 = "문자열";
        // 백틱(``)
        var string3 = `문자열`;
  • "''" , '""' → 이렇게도 사용 가능(안에 위치한 따옴표는 문자열로 인식)

1.2 표현식

코드를 실행시켜 나타나는 값을 보세요.

        let txt = 'ABCDEFGHIJKLMNABC';
        let text_two = 'mom said \'hello world\'';
        let text_three = "mom said 'hello world'";
        let number = '100';

        document.write(number + number, '<br>');
        document.write(Number(number) + Number(number), '<br>');
        document.write(parseInt(number) + parseInt(number), '<br>');
        document.write(+number + +number, '<br>');

        document.write(`txt : ${txt}<br>`);
        // 문제 : 100 + 100 = 200이라고 출력을 해주세요.
        document.write(`100 + 100 = 200<br>`);
        document.write(`${number} + ${number} = ${number * 2} <br>`);
        document.write(number, '+', number, '=', number*22, '<br>');

        document.write(`txt.length : ${txt.length}<br>`);
        document.write(`txt[1] : ${txt[1]}<br>`);

        document.write(txt.indexOf("F"), '<br>');
        // indexOf는 정규 표현식을 허용 X
        document.write(`txt.indexOf("F") : ${txt.indexOf("F")}<br>`);
        document.write(`txt.search("F") : ${txt.search("F")}<br>`);

        document.write(`txt.indexOf("FG") : ${txt.indexOf("F")}<br>`);
        document.write(`txt.search("FG") : ${txt.search("F")}<br>`);

        document.write(`txt.indexOf("Z") : ${txt.indexOf("Z")}<br>`);
        document.write(`txt.search("Z") : ${txt.search("Z")}<br>`);

        let regExp = /CD/;
        // document.write(`txt.indexOf(regExp) : ${txt.indexOf(regExp)}`);
        document.write(`txt.search(regExp) : ${txt.search(regExp)}<br>`);

        document.write(`txt.lastIndexOf : ${txt.lastIndexOf("F")}<br>`);
        document.write(`txt.lastIndexOf : ${txt.lastIndexOf("FGH")}<br>`);
        document.write(`txt.lastIndexOf : ${txt.lastIndexOf("B")}<br>`);
        document.write(`txt.indexOf : ${txt.indexOf("B")}<br>`);
        document.write(txt[0]+txt[1]+txt[2], '<br>');
        document.write(txt[0], txt[1], txt[2], '<br>');

        // slice(시작인덱스, 종료인덱스) : 시작인덱스부터 종료인덱스 - 1까지 반환합니다.
        // substr(시작위치, 길이) : 시작인덱스부터 길이만큼 반환합니다.
        document.write(`txt.slice(0, 3) : ${txt.slice(0, 3)}<br>`);
        document.write(`txt.substring(0, 3) : ${txt.substring(0, 3)}<br>`);
        document.write(`txt.substr(0, 3) : ${txt.substr(0, 3)}<br>`);

        document.write('abcdef'.replace('cde', 'hojun'));
        document.write(`txt.replace('ABC', 'hojun') : ${txt.replace('ABC', 'hojun')} <br>`);
        document.write(`txt.replace('ABC', 'hojun') : ${txt.replace(/ABC/g, 'hojun')} <br>`);

        document.write(`<br><hr><br>`);

        document.write(`txt.toUpperCase() : ${txt.toUpperCase()} <br>`);
        document.write(`txt.toLowerCase() : ${txt.toLowerCase()} <br>`);

        document.write(`<br><hr><br>`);

        document.write(txt.includes('Z'), '<br>');
        document.write(txt.includes('BC'), '<br>');
        document.write(txt.startsWith('BCD'), '<br>');
        document.write(txt.startsWith('ABC'), '<br>');
        document.write(txt.endsWith('AB'), '<br>');
        document.write(txt.endsWith('ABC'), '<br>');
        
        //문맥을 봐야 합니다.
        // document.write(number + number, '<br>');
        // document.write(number + 10, '<br>');
        // document.write(number - 10, '<br>');
        // document.write(number * 10, '<br>');

        // document.write(typeof(number), '<br>');
        // document.write(typeof(+number), '<br>');
        // document.write(typeof(null), '<br>'); // 심각
        // document.write(typeof(NaN), '<br>'); // 심각
        // document.write(typeof(Infinity), '<br>');
        // document.write(typeof([]), '<br>'); // 심각
        // document.write(typeof({}), '<br>');
        // document.write(typeof(''), '<br>');
        // document.write(typeof(0), '<br>');

        // console.log(0 + '');
        // console.log(Infinity + '');
        // console.log(true + '');
        // console.log({} + ''); // 심각
        // console.log(({}) + ''); // 심각
        // console.log([] + ''); // 심각
        // console.log([1, 2, 3, 4] + ''); // 심각

2. Boolean

참(true) 거짓(false)을 나타낸다.

2.1 사용예시

        let value1 = 30;
        let value2 = 50;

        console.log(value1 > value2);
        console.log(value1 >= value2);
        console.log(value1 < value2);
        console.log(value1 <= value2);
        console.log(value1 == value2);
        console.log('----------');

        value1 = 30;
        value2 = '30';
        console.log(value1 == value2);
        console.log(value1 === value2);
        console.log('----------');

        console.log(value1 != value2);
        console.log(value1 !== value2);

        console.log('----------');
        value1 = true;
        value2 = false;
        console.log(!value1);
        console.log(!!value2); // 강조!! 정말 많이 사용합니다.

결과

2.2 혼란스러운 경우 모음

		document.write(`1. ${'0' == 0}<br>`);
        document.write(`2. ${'0' === 0}<br>`);
        document.write(`3. ${false == 0}<br>`);
        document.write(`4. ${false === 0}<br>`);
        document.write(`5. ${true == 1}<br>`);
        document.write(`6. ${false == '0'}<br>`);
        document.write(`7. ${false == 'false'}<br>`);
        document.write(`8. ${0 == ''}<br>`); // 주의
        document.write(`9. ${false == ''}<br>`); // 주의
        document.write(`10. ${false == null}<br>`); // 주의
        document.write(`11. ${false == undefined}<br>`); // 주의
        document.write(`12. ${NaN == NaN}<br>`); // false 주의
        document.write(`13. ${NaN === NaN}<br>`); // false 주의
        document.write(`14. ${isNaN(undefined)}<br>`); // true 주의
        document.write(`15. ${isNaN(null)}<br>`); // false 주의
        document.write(`16. ${isNaN(NaN)}<br>`); // true 주의
        document.write(`17. ${Number.isNaN(undefined)}<br>`); // true 주의
        document.write(`18. ${Number.isNaN(null)}<br>`); // true 주의
        document.write(`19. ${Number.isNaN(NaN)}<br>`); // true 주의
        document.write(`20. ${![]}<br>`); // false 주의
        document.write(`21. ${!{}}<br>`); // false 주의

        if ([]) {
            document.write('hello world 1');
        }
        if ({}) {
            document.write('hello world 2');
        }
        if ('') {
            document.write('hello world 3');
        }
        if (undefined) {
            document.write('hello world 4');
        }

        console.log('----------------');
        console.log(`1 ${!!undefined}`);
        console.log(`2 ${!!null}`);
        console.log(`3 ${!!NaN}`);
        console.log(`4 ${!!Infinity}`);
        console.log(`5 ${!![]}`); // 주의
        console.log(`6 ${!!{}}`); // 주의
        console.log(`7 ${!!''}`); // 주의
        console.log(`8 ${!!0}`);
        console.log(`9 ${!!'hello world'}`);
        console.log(`10 ${!!-100}`);

        console.log('----------------');
        console.log('드모르간 법칙');
        // or : ||
        // and : &&
        const x = 0;
        const y = 1;
        console.log(!(x || y) === (!x && !y));
        console.log(!(x && y) === (!x || !y));

        console.log(+false);
        console.log(+true);
        console.log(false*1);
        console.log(true*1);

3. Object

// 객체(object)
        // 함수는 후에 자세히 다룹니다.
        function sum(x, y) {
            return x + y
        }
        // TMI입니다. 뒤에서 다룰 내용이에요.
        // console.log(typeof sum);
        // sum.value = 'hojun';
        // console.log(console.dir(sum));
        // console.log(sum.value);
        // console.log(typeof sum);
        let person = {
            //key: value
            name: '이호준',
            age: 10,
            height : 30,
            weight : 40,
            이력 : {'첫번째직장' : '하나', '두번째직장' : '둘'},
            기능 : sum,
            출력 : console.log,
        }
        person.소속 = '바울랩';

        document.write(`제 이름은 ${person.name} 입니다.<br>`);
        document.write(`제 이름은 ${person['name']} 입니다.<br>`);

        document.write(`제 나이는 ${person.age} 입니다.<br>`);
        document.write(`제 키는 ${person.height} 입니다.<br>`);

        document.write(`제 두번째 직장은 ${person['이력']['두번째직장']} 입니다.<br>`);
        document.write(`제 두번째 직장은 ${person.이력.두번째직장} 입니다.<br>`);

        document.write(`제 기능은 ${person['기능'](100, 200)} 입니다.<br>`);

        // 문제
        // 1번 : 저에게 3번째 직장이 생겼습니다. 직장이름은 위니브입니다. 데이터를 넣어주시고 아래와 같이 출력되게 해주세요.
        // 출력결과 : 제 세번째 직장은 위니브 입니다.
        person.이력.세번째직장 = '위니브';
        document.write(`제 세번째 직장은 ${person.이력.세번째직장} 입니다.<br>`);
        document.write(`제 세번째 직장은 ${person.이력.두번째직장} 입니다.<br>`);
        person.이력 = {'세번째직장' : '위니브'};
        document.write(`제 세번째 직장은 ${person.이력.세번째직장} 입니다.<br>`);
        document.write(`제 세번째 직장은 ${person.이력.두번째직장} 입니다.<br>`);


        // 문제2
        // 이호준의 세번째 직장에 두번째 직책을 출력해주세요.
        let 이호준상세정보 = {
            이력 : {
                '첫번째 직장': {
                    '회사이름': '바울랩',
                    '부서': '경영지원',
                    '직책': '대표',
                },
                '두번째 직장': {
                    '회사이름': 'SEMSANG',
                    '부서': '경영지원',
                    '직책': '대표',
                },
                '세번째 직장': {
                    '회사이름': 'SINHUN',
                    '부서': '경영지원',
                    '직책': {
                        '첫번째직책':'사원',
                        '두번째직책':'대표',
                    },
                },
            },
        }
        console.log(이호준상세정보.이력['세번째 직장'].직책.두번째직책);
        // 따옴표를 써야 하는 이유?
        // 데이터 저장하는 경우 띄어쓰기가 있을 수도 있기 때문(회사의 컨벤션 따라가시면 됩니다.)

        let txt = 'hello'
        let txt2 = {
            0: 'h',
            1: 'e',
            2: 'l',
            3: 'l',
            4: 'o',
        }
        console.log(txt[1]);
        // console.log(txt.1);
        console.log(txt2[1]);
        // 이거 2개를 해줄 수 있는게 map
        // console.log(txt2.1);
        // console.log(txt2.{'one':'1'});

        console.log(String(10));
        console.log('1234'.replace('23', '99'));

        console.log(Object.keys(person));
        console.log(Object.values(person));
        console.log(Object.entries(person));
        
        // why? 이걸 해결하기 위해 나온 것이 map!
        // console.log(person.values);
        // console.log(person.keys);
        // console.log(person.entries);

Object.prototype의 경우에 대해서 알아보기

profile
멋진 프론트엔드 개발자를 위하여!

0개의 댓글