자바스크립트 기초 문법 정리 - 2

citron03·2021년 12월 19일
0

html, css, js

목록 보기
4/43

function(함수)

  • 파이썬은 def ~ ( ) :를 이용해 함수를 만들지만,
    자바스크립트는 function ~( ) { } 를 통해서 함수를 만든다.
  • 객체 내에 함수를 생성할 때는 ~ : function( ){ }이다.
  • 매개변수가 여러 개라면, 순서대로 대입된다.
  • 객체 내부의 함수로 객체의 원소 값을 바꾸려면 this.~ = "바꿀 값"을 사용한다.
  • return을 통해 값을 반환할 수도 있다.
  • Java처럼 생성자를 만들어 객체를 생성할 때 사용할 수 있다.
  • prototype을 통해서 객체를 상속받을 수도 있다. (상속 받은 객체의 정보를 공유받음)
  • 여러 개의 값을 return하기 위해서는 배열 / 객체를 이용한다.
// function을 사용해서 함수를 만들 수 있다.
function printingALL(listNames){
  console.log("names :", listNames)
}

listNames = ["Kim", "Lee", "Park"];
printingALL(listNames); 
// 결과 = names : [ 'Kim', 'Lee', 'Park' ]

------------------------------------------------------

// 객채 내부에 함수 만들기
const names = {
  myName: "Kim",
  friendName: "Jane",
  addName: function(newName){
    this.myName = newName;// 객체 내부의 원소를 변경하기 위해서 this.~을 사용한다.
    return true;
  },
}

returnValue = names.addName("nanananan");

console.log(names.myName, names.friendName, returnValue);
// 출력 = nanananan Jane true

객체 생성자 만들기

  • 객체 생성자를 만드는 방법으로 new Object()를 사용해 객체에 프로퍼티를 주입하는 방법이 있다.
  • 또는 함수를 통해서 객체를 만들 수도 있다.
  • prototype을 통해서 객체에서 공통적인 부분을 상속받아 사용할 수 있다.
    이렇게 하면 메모리를 아낄 수 있다.

function game(genres, price){
  this.genres = genres;
  this.price = price;
  // 아래의 프로토타입의 함수는 어떤 객체를 만들어도 동일하다.
  game.prototype.printAll = function(){
    console.log(this.genres, this.price);
    alert(this.genres + "은(는) " + this.price + "$ 입니다.");
  }
}

// 생성자 함수로 객체 생성
let newGame = new game("battle", 5000);
newGame.printAll(); // 객체의 함수 사용

let lastGame = new game("RPG", 3600);
lastGame.printAll();

🍳 자바스크립트는 왼쪽에서 오른쪽으로 코드를 읽어나간다. 🍳

// 다음의 코드는 오류가 나지 않는다.
let a = 34, b = a;
console.log(a, b);

// 다음의 코드는 오류가 발생한다.
let a = b, b = 34;
console.log(a, b);

조건문

  • if와 else if, else를 사용할 수 있다.
    if 내부의 조건문에는 boolean 값만 사용이 가능하다.
if(typeof 1 === typeof "33"){
  console.log("F");
}else if(1 > 33){
  console.log("Z");
}else{
  console.log("A"); // "A"출력됨
}
  • &&나 ||나 !==, ===, ==, <=, >=와 같은 연산자도 사용 가능하다.
    🍘 ==는 자료형에 관계없이 값만 비교하는 반면(자료형 변환 O), ===는 변수의 자료형이 같은지부터 엄격하게 비교한다.
if(typeof 1 !== typeof 33){
  console.log("F");
}else if(false && false){
  console.log("Z");
}else if(true || false){
  console.log("A"); // "A"가 출력된다
}

반복문

  • for문을 사용할 수 있다.
    🍕 세 가지 방법이 있는데, 자바나 C언어에서 사용했던,
    for(let i = 0; i < 10; i++){ }
    방법과,
    🍔 주로 파이썬에서 사용했던 것과 유사하지만 완전 다른
    for (i in ["a", "b", "C"]) { } 와 같은 방법이 있다.
    in을 사용하면, index의 값이 i에 담기게 된다.
    이를 통해서 객체나 리스트 의 값에 접근할 수 있다.
    🍟 그리고 마지막으로 of를 사용하는 방법으로 파이썬에서의 in과 유사하다.
    for (i of ["a", "b", "C"]){ }
    of를 사용하면, i에는 순서대로 배열의 원소"a", "b", "c"가 담기게 된다.
let list_i = [];
for(let i = 0 ; i < 5; i++){
  list_i.push(i);
  list_i.push(i);
}
console.log(list_i);
// [ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4 ]
let sum = "";
for (i in list_i){
  sum += i;
}
console.log(sum); 
// "0123456789"
let sum_integer = 0;
for(i of list_i){
  sum_integer += parseInt(i);
}
console.log(sum_integer);
// 20
  • for문에서 in을 사용하는 반복문은 객체에 더 최적화되어 있다.
const direction = {
  right: "east",
  left: "west",
  up: "north",
  down: "south",
}
for(let i in direction){
  console.log(i, direction[i]);
}
// 출력의 결과물은 다음과 같다.
// right east
// left west
// up north
// down south
  • while문도 사용할 수 있으며, break나 continue도 사용가능하다.
let a = 1;
while(true){
  if(a > 3) // a가 4가 되면 반복문 break
    break;
  if(a === 1){
    a += 1;
    continue; // 다음 반복으로 건너 뜀
  }
  // a === 1일때 실행 X
  a += 1;
  console.log(a);
}
profile
🙌🙌🙌🙌

0개의 댓글