자바스크립트 기초문법

핸디·2021년 6월 24일
0

자바스크립트

목록 보기
1/4

1. 자바스크립트에 대해

브라우저는 HTML을 열고, HTML은 CSS와 JS를 가져옴
CSS와 JS파일을 여는 것으로는 아무 일도 일어나지 않음

css는 html위쪽에서, js는 body안 뒤쪽에서 가져오자

<!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">**
    <title>Momentum App</title>
</head>
<body>
    <div class="hello">
        <h1>Grab me!</h1>
    </div>
    
    **<script src="app.js"></script>**
</body>
</html>

2. 변수

기본적으로 const를 쓰고 필요할 때만 let을 쓰되, var은 쓰지 말 것!

const는 변수 값을 변경할 수 없고 , let은 변경할 수 있다.
var는 코드가 밑에서 뭘할지 알 수가 없음

예시
const a=10;
let b=10;
b=11; (가능)
a=11; (불가능)

const flag=true;

list=[1,2,"hello",false, ..]; //list에는 여러 종류 변수 넣을 수 있음
list.push("sun"); //리스트에 새로운 원소 삽입

3. 함수

function sayHello(nameOfPerson,age){
  console.log("hello my name is "+nameOfPerson+"and I'm "+age+"years old.");
  
function plus(a,b){
  return a+b;
}

4. Object

Object는 c++의 클래스와 유사하다.
js에서 html의 element들을 읽어올 뿐만 아니라 변경할수도 있다.

const player={
  name:"nico",
  age:20,
  points:10,
  fat=true,
  plus:function(a,b){ //그냥 함수 선언할때랑 object안에서 쓰는 법 다름!
    return a+b;
  },
};

console.log(player);
console.log(player.name);
//object안의 원소들은 수정할 수 있다!
//다만, constant 전체를 하나의 값으로서 업데이트하려고 할때 오류 발생

player.lastName="potato";
console.log(player); -> player Object안에 lastname이란 변수 추가됨

cf) JS에서 값 확인할때 '===' (= 3개!!) 쓴다!!

5. JS에서 html element 불러오기

getElementById, getElementsByClassName, querySelector등의 방법이 있다.
querySelector는 css selector이고 하나의 element만 가져온다.
여러개 가져오고 싶다면 querySelectorAll 사용

const title=document.getElementById("title");
console.log(title);
title.innerText="got you!"; //title을 js에서 변경 가능
console.log(title.id);
console.log(title.className);

const hellos=document.getElementsByClassName("hello");
console.log(hellos);


const title=document.querySelector(".hello h1"); //hello 클래스 안의 h1 element
//querySelector는 하나의 element만 가져옴! .hello h1여러개 있어도 맨 첫번째것만
//.hello h1 여러개 가져오고 싶으면 querySelectorAll 사용
// . -> 클래스, # -> id
console.log(title);
console.dir(title) ; //해당 element에 대한 정보(property) 보여줌

0개의 댓글