[JavaScript] Object (this), Array

 const superman = {

    name: 'clark',
    age: 33,
    fly: function(){
        console.log("Flying")
    }
}

superman.fly();

"Flying"

method: 객체 property로 할당 된 function

function 생략가능 

const superman = {
    name: 'clark',
    age: 33,
    fly(){
        console.log("Flying")
    }
}

superman.fly();


this 

const user = {
    name:"Mike",
    sayHello: function(){
        console.log(`Hello, I'm ${this.name}`);
    }
}

user.sayHello();

use.name 으로하면 Error 발생


*화살표 함수는 일반함수와 달리 자신만의 This를 가지지 않음. (외부에서 값을 가져옴)

let boy = {
    name: "Mike",
    sayHello : () => {
        console.log(this);
    }
}

boy.sayHello();

this !=boy  


브라우저: window

Node js: global



let boy = {
    name: "Mike",
    showname: function () {
        console.log(boy.name)
    }
};

let man = boy;

man.name = "Tom"

console.log(boy.name);


"Tom"


This 이용

let boy = {
    name: "Mike",
    showname: function () {
        console.log(this.name)
    }
};

let man = boy;
boy = null;


man.showname();

boy를 bull 했지만 this 를 써서 해당 객체를 불러옴

"Mike"



*Array

배열은 문자뿐 아니라 숫자, 객체, 함수등도 포함 가능


length: 배열의 길이

students.length


push(): 배열 끝에 추가

let days = ["mon", "tue", "wed"];
days.push("thr")

console.log(days);
["mon","tue","wed","thr"]


pop(): 배열 요소 제거

let days = ["mon", "tue", "wed"];
days.pop()

console.log(days);
["mon","tue"]


shift, unshift 배열 앞에 제거/추가

추가
days.unshift("sun");

console.log(days) = ["sun", "mon", "tue", "wed"];


제거
days.unshift();

console.log(days) = ["mon", "tue", "wed"];

여러요소 한 번에 가능


반복문: for

let days = ["mon", "tue", "wed"];

for(let index = 0; index < days.length; index++){
    console.log(days[index])
}
// 0부터 시작하고, 3보다 작고, 인덱스 +1   반복..



let days = ["mon", "tue", "wed"];

days.push("thu");
days.unshift("sun");

for (let index=0; index < days.length; index++) {
    console.log(days[index]);
}

"sun"
"mon"
"tue"
"wed"
"thu"





반복문: for ... of

let days = ["mon", "tue", "wed"];

for(let day of days){
    console.log(day)
}

index를 못얻는 단점이 있음



let days = ["mon", "tue", "wed"];

days.push("thu");
days.unshift("sun");

for (let x of days){     // x는 아무렇게나 넣어도 됨
    console.log(x);
}


"sun"
"mon"
"tue"
"wed"
"thu"


Popular posts from this blog

[Python] Dictionary

[Visual Design 2/3]

[JavaScript] For loop , Function