엘리스 6일차 월요일 실시간 강의 javascript

치즈말랑이·2022년 4월 11일
0

엘리스

목록 보기
7/47
post-thumbnail

자동줄바꿈 word wrap 설정하는법: https://jaeu0608.tistory.com/83
vsc 확장프로그램 git graph: git log 대체
ESLint: 통합문법가이드

1. 이고잉님 강의

run.html

run.html

<html>
<body>
    <h1>Script tag</h1>
    1+1
    <script>
        document.write(1+1);
    </script>
    <h1>Event</h1>
    <input type="button" value="hi" onclick="
                                             alert('hi')
                                             ">
    <input type="button" value="speech" onclick="
                                                 speechSynthesis.speak(new SpeechSynthesisUtterance('꼭이요!'));
    ">
</body>
</html>

javascript를 html 파일 내부의 script태그 안에 작성하여 사용할 수 있다. head, body 아무데나 괜찮 --- 사용법1
onclick은 마우스를 클릭하면 작동되는 속성이다. 이 onclick안에도 js가 들어가있다. --- 사용법2
alert는 팝업창(모달창)이고, speechSynthesis는 위의 코드에서 꼭이요를 번역기같은 말투로 음성메세지가 나오게 하는 것이다.

datatype.html

datatype.html

<html>
    <body>
        <h1>숫자</h1>
        <script>
            document.write(1); // integer 가장많이사용되는데이터타입
            document.write('<br>');
            document.write(1.1);
            document.write('<br>');
            document.write(1+1);
            document.write('<br>');
            document.write(2*2);
            document.write('<br>');
            document.write(2/2);
            document.write('<br>');
            document.write(4/2);
            document.write('<br>');
            document.write(Math.random());
            document.write('<br>');
            document.write(Math.PI)
            document.write('<br>');
            document.write(Math.pow(2,3));
            </script>

            <h1>문자열 String</h1>
            <script>
                document.write('Hello World <br>');
                document.write("Hello \
                 World <br>");
                document.write(`Hello 
                World <br>`);
                document.write('adfas'.length + '<br>');
                document.write('hell world'.replace('hell', 'hello') + '<br>');
                document.write('dhkdn');
                document.write('<br>');
                document.write(1+2);
                document.write('<br>');
                document.write('1'+'2');

            </script>
    </body>
</html>

html에서는 1+1 이라고 쓰면 웹화면에 1+1 이라고 출력되지만, 자바스크립트 코드로 1+1를 쓰면 계산이되서 2라고 나온다.
html: 정적, 자바스크립트: 동적
가장 많이 쓰는 데이터타입은 숫자 integer와 문자열 string이다.
Math.random: 랜덤 숫자 출력
Math.PI: 파이 출력
Math.pow(x,y): x^y 출력

여기서 Math, document 이런것들은 모두 객체이다.

variable.html

variable.html

<html>
<body>
    <h2>변수</h2>
    <script>
        let a=1;
        let b=2;
        console.log(a+b);
        a=3;
        console.log(a+b);
    </script>

    <h2>변수는 왜 쓰는가?</h2>
    <script>
        let 가격 = 10000;
        let 부가가치세율 = 0.1;
        let 부가가치세 = 가격 * 부가가치세율
        console.log(부가가치세); // 10000; 가격, 0.1 부가가치세율
        // 변수는 데이터에 이름을 붙인 것
    </script>
</body>
</html>

변수 선언할때 let 사용

flow-control.html

flow-control.html

<html>
<body>
    <h1>Boolean</h1>
    <script>
        console.log(true);
        console.log(false);

    </script>
    <h1>Comparison operator</h1>
    <script>
        console.log(1 === 1);
        console.log(1 === 2);
        console.log(2 > 1);
        console.log(2 < 1);
    </script>
    <h1>Conditional Statements</h1>
    <script>
        console.log(1);
        if (false) {
            console.log(2);
            console.log(3);
        }
        console.log(4);
    </script>
    <h1>Login</h1>
    <script>
        let input_id = prompt('id?');
        let id = 'egoing';
        if (input_id === id) {
            alert ('어서오세요!');
        } else {
            alert('누구세요');
        }
    </script>
</body>
</html>

console.log 명령어를 하면 웹브라우저에서 검사를 눌렀을때 나온 개발자 콘솔창에 출력된다.
prompt는 입력할수있는 팝업창을 띄운다.

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>WEB - Welcome</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <script>
            console.log(this); // 화면 전체의 정보
        </script>
        <input type="button" onclick="console.log(this);" value="1"> <!-- 이 버튼에 대한 정보 -->
        <input type="button" onclick="console.log(this);" value="2"> <!-- 이 버튼에 대한 정보 -->
        
        <input type="button" value="night" onclick="
        // 만약에 이 버튼의 value 값이 night라면 아래 코드가 실행되고,
        if (this.value === 'night') {
        document.querySelector('body').style.backgroundColor = 'black';
        document.querySelector('body').style.color = 'white';
        this.value = 'day';
        } else {
        // 아니라면 아래 코드가 실행된다.
        document.querySelector('body').style.backgroundColor = 'white';
        document.querySelector('body').style.color = 'black';
        this.value = 'night';
        }
        ">
<!-- 
        <a href="">오우</a>
        <input type="button" value="night" onclick="
        // alert('야간!');
        document.querySelector('body').style.backgroundColor = 'black';
        document.querySelector('body').style.color = 'white';
        ">

        <input type="button" value="day" onclick="
        document.querySelector('body').style.backgroundColor = 'white';
        document.querySelector('body').style.color = 'black';
        "> -->
        <!-- onmouseleave = "alert('안녕히가세요');" -->
        <!-- document.querySelector('body').style.backgroundColor = 'red'; -->
        <!-- document.querySelector('#container').style.backgroundColor = 'blue'; -->
        

    </body>
</html>

css에서 selector 선택자 개념이 나왔는데, 자바스크립트에도 그런게 존재한다.
document.querySelector()에서 괄호 안에 선택자를 형식에 맞게 넣는다. id는 #hello, class는 .class, 둘다아니면 그냥 'body'

여기서 this의 개념이 나온다.
그냥 this는 화면 전체의 정보이다. 하지만 버튼 안에서 this를 사용하면 그 버튼을 가리킨다.

코치님 강의

이고잉님이 알려준것과 다른 방법으로 js를 사용했다.
js파일을 따로 만든 후 html head에서 불러오는 방법이다.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <script src="script.js" defer></script>
    <title>Document</title>
</head>
<body>
    <button>버튼</button>
</body>
</html>

defer: html을 먼저 불러오고 그다음에 js파일을 불러온다.
html 파싱 -> defer -> DOM content loaded

script.js

function hello() {
    console.log('hello');
}

hello();


console.log('hello world!');

for (let i = 0; i < 5; i++) {
    console.log(i);
} 
let i = 0;

console.log(i === 30)

if (i === 30) {
    console.log('true')
} else {
    console.log('false')
}

i === 30 ? console.log('true') : console.log('false')


while (i<5) {
    i++;
    console.log(i);
}

while (i<5) {
    console.log(i);
    i++;
}

console.log(null == undefined);
console.log(null === undefined);

function printMessage(message, times) {
    // consolee.log(message, times);
    for (let i = 0; i < times; i++) {
        console.log(message);
    }
    console.log(`Value of i is ${i}`);
}
printMessage('hello', 35)
// 함수의 변수 개수 다르게줘도 상관없음
// 자바스크립트의 목적: 약간 에러있어도 일단 실행 -> 명확하게 하기 위해 typescript 사용

// Array 순서가 있음
let a = ['a', 'b'];
console.log(a[0])

// for문으로 내용물 다 빼는것과 같다.
a.map(function (aa) {
    console.log(aa)
})

// object
let b = {'a': 1, 'b':2};
delete b.a

function onClick() {
    console.log('clicked');
}

const button = document.querySelector('button');
button.addEventListener('click', onClick())

==, ===

자바스크립트는 ==와 ===가 있는데, ==는 값만 같으면 true이고 ===는 데이터타입까지 맞아야 true이다.
null == undefined는 true
null === undefined는 false이다.

삼항연산자

i === 30 ? console.log('true') : console.log('false')

명제를 ? 앞에 쓰고 : 좌변에 참일때 실행되는 코드를, 우변에 거짓일때 실행되는 코드를 작성한다.

`${변수}`

파이썬의 f문법과 비슷한게 있는데 `${변수}` 이다. `는 백틱

console.log(`Value of i is ${i}`);

hoisting

자바스크립트는 문법을 엄격하게 지키기 보다는 빨리빨리 개발하는것을 목표로 하기 때문에 hoisting이 가능하다.
hoisting: function이 정의되기 전에 불러와도 에러 안나게 하는 기능

hello();
hello();
function hello() {
 console.log('Hello!');
 console.log('Welcome to JavaScript');
}

hello 함수가 정의되기 전에 hello()를 호출해도 정상작동된다.

var, const, let

변수를 선언할때 var, const, let을 사용할 수 있지만, var는 사용하지 않는것을 권장한다. function 전체에 걸쳐 존재하기 때문.
https://jodev.kr/entry/JavaScript-var%EB%A5%BC-%EA%B6%8C%EC%9E%A5%ED%95%98%EC%A7%80-%EC%95%8A%EB%8A%94-%EC%9D%B4%EC%9C%A0

if (...) {
 let x = 5;
 ...
}
// can't access x here
if (...) {
 var x = 5;
 ...
}
// x is 5 here
function printMessage(message, times) {
 for (var i = 0; i < times; i++) {
 console.log(message);
 }
 console.log('Value of i is ' + i);
}
printMessage('hello', 3);
console.log(i)

console.log('Value of i is ' + i); 여기서는 정상적으로 var i 를 불러와서 출력이 된다. var는 function scope 단위이기 때문. 하지만 맨아래 console.log(i)에서는 에러가 난다. function scope밖에 있기 때문이다.

만약 i를 let으로 선언하면 console.log('Value of i is ' + i); 이것도 에러가 난다.

const로 선언하면 그냥 for문에서 에러가 난다. const는 더이상 수정이 불가능하기 때문.

'' == '0' // false
'' == 0 // true
0 == '0' // true
NaN == NaN // false
[''] == '' // true
false == undefined // false
false == null // false
null == undefined // true
'' === '0' // false
'' === 0 // false
0 === '0' // false
NaN == NaN // still weirdly false
[''] === '' // false
false === undefined // false
false === null // false
null === undefined // false

Array, Object

Array는 리스트,배열과 같은 것이다.
Object는 dict처럼 key value가 있는것이다.

Array

배열의 모든 아이템을 꺼낼때는 두가지 방법이 있다.

let groceries = ['milk', 'cocoa puffs', 'tea'];
for (let i = 0; i < groceries.length; i++) {
 console.log(groceries[i]);
}
for (let item of groceries) {
 console.log(item);
}

Object

const prices = {};
const scores = {
 'peach': 100,
 'mario': 88,
 'luigi': 91
};
console.log(scores['peach']); 
const scores = {
 peach: 100,
 mario: 88,
 luigi: 91
};
console.log(scores['peach']);

key 값을 ''로 감싸도 되고 안감싸도 된다.
scores.peach 혹은 scores['peach'] 로 value값을 불러온다.

삭제할수도있다.

delete scores.peach;

배열하고는 약간 다른 방법으로 아이템들을 꺼낸다.

for (key in object) {
// … do something with object[key]
}
for (let name in scores) {
console.log(name + ' got ' + scores[name]);
}

Selector

document.querySelector('css selector'); // first element
document.querySelectorAll('css selector'); // all elements

git 에러 해결

깃허브를 main branch로 만들어놓고 로컬에서 master branch로 push를 해서 꼬여버렸다.
그래서 https://somjang.tistory.com/entry/Git-rejected-master-master-non-fast-forward-%ED%95%B4%EA%B2%B0-%EB%B0%A9%EB%B2%95 여기 나온거 처럼

git push origin +main

이 명령어로 진행을 하고, master branch는 삭제했다. merge하려고했는데 안됨.

자바스크립트 그외 문법

<br>

자바스크립트 코드 내에서 줄바꿈 코드인 br은 아무데나 넣을 수 있다.

document.write(1);
document.write("<br>");
document.write("hello" + "<br>");
document.write("hel<br>lo");

새로운 줄에 단독으로 써도 되고, +"" 형식으로 써도 되고, ""안에 넣어도 된다.

const readline = require('readline');

const rl = readline.createInterface({
	input: process.stdin,
    output: process.stdout,
})

rl.on('line', function(x) {
	if ( x === 'ho' ) {
    	rl.close();
    } else {
    	console.log(x);
    }
}).on('close', function() {
	process.exit();
});

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

const arrayToHandle = input[0].split(" ");
    const N = input[1];
    arrayToHandle.sort(function(a,b) {
        return parseInt(b)-parseInt(a);
    })
    console.log(arrayToHandle[N-1]);

혹은

    const arrayToHandle = input[0].split(" ").map((i) => parseInt(i));
    const N = input[1];
    
    //첫번째 줄 정렬
    arrayToHandle.sort(function(a,b){
        return b-a
    })
profile
공부일기

0개의 댓글