ETC

[바닐라 JS로 크롬 앱 만들기] Javascript 문법

alsruds 2023. 4. 6. 04:46

● 변수

// 브라우저 콘솔 창에 로그 띄우기 : console.log()
// 변수 선언1 : const   (cannot change) - always
// 변수 선언2 : let                     - sometimes
// 변수 선언3 : var     (never use)
// 데이터 타입 : true / false / null / undefined

const a = 5;     
const b = 2;
let myName = "cindy";

console.log(a+b);
console.log(a*b);
console.log(a/b);

myName = "sandy";
console.log("your name is " + myName);

 

 배열

// array (배열)
const mon = "mon";
const tue = "tue";
const wed = "wed";
const days = [mon, tue, wed];   # 변경 가능

// Get Item from Array
console.log(days[0]);

// Add one more day to the array
days.push("thur");
console.log(days);

 

 객체

// Objects
const player = { # 안에 내용 변경 가능
    name: "cindy",
    points: 10,
    getscore: true,
};

console.log(player);
console.log(player.name);   # player["name"]

// 업데이트
player.getscore = false;
console.log(player.getscore);

// 추가
player.lastName = "potato";
console.log(player);

 

 함수

// Functions
function sayHello(name, age) {
    console.log("Hello! My name is "+ name +','+age);
}

sayHello("nico", 1);
sayHello("cindy", 2);

function plus(a,b){
    console.log(a+b);
}
plus(10,20);

const newPlayer = {
    name: "cindy",
    sayHello: function(othername) {
        console.log("hello! "+ othername);
    },
};

console.log(newPlayer.name);
newPlayer.sayHello("nico");

 

》 계산기

// calculator
const calculator = {
    add: function(a,b) { console.log(a+b); },
    minus: function(a,b) { console.log(a-b); },
    multi: function(a,b) { console.log(a*b); },
    div: function(a,b) { console.log(a/b); },
    powerof: function(a,b) {console.log(a**b); },
};

calculator.add(10,20);
calculator.minus(30,15);
calculator.multi(2,5);
calculator.div(25,5);
calculator.powerof(2,3);

 

Return

// stop using console.log()
// function code 자체에서 답을 얻기 > return
const age = 20;
function calAge(beforeAge) {
    return beforeAge + 2;
}
const afterAge = calAge(age);
console.log(afterAge);

const calculator = {
    plus: function(a,b) {return a+b;},
    minus: function(a,b) {return a-b;},
    times: function(a,b) {return a*b;},
    divide: function(a,b) {return a/b;},
    power: function(a,b) {return a**b;},
};
const plusResult = calculator.plus(2,3);
const minusResult = calculator.minus(plusResult,2);
console.log(plusResult);
console.log(minusResult);

 

 조건문

// if
// age calculator
let age = prompt("How old are you?");    # prompt: 입력창 띄우기
console.log(age);
console.log(typeof age);

// string > number
// parseInt : 적용 안되면 NaN 출력 (Not a Number)
age = parseInt(prompt("How old are you?"));

// check NaN : isNaN()
console.log(isNaN(age));

if(isNaN(age) || age <= 0){
    console.log("Please write a number");
} else if (age<18) {
    console.log("You are too young");
} else if (age >=18 && age <=50) {
    console.log("You can drink");
} else if (age === 100) { // !==
    console.log("wow you are wise");
} else {
    console.log("You can't drink");
}