자바스크립트 기본 2

이정우·2021년 10월 19일
0

JS

목록 보기
3/4

< script>
function setName(obj) {
obj.name = "Lee";
obj = new Object();
obj.name = "jeungwoo";
}
const person = new Object();
setName(person);
alert(person.name);
< /script>

스택 생성 순서 : person 만들어 힙 1번 주소를 가르킴. 함수 호출해서 첫 obj.name이 person과 같은 힙 영역을 가르키면서(1번) 함수 전용 스텍 자리에 새로 생성. Lee값을 넣은 후 새로운 obj 생성하는데 이때 원래 있던 obj가 원래 있던 주소 말고 새로운 주소인 2번 힙 자리 가르킴. 그 새로운 2번 힙 자리에 새로운 jeungwoo가 입력됨. 우리가 원하는것은 person.name! 그래서 Lee가 출력됨. 만들어진 스텍은 person과 obj2개. heap에는 Lee와 jeungwoo 2개 생성됨.

jeungwoo를 출력하고자 한다면
< script>
function setName(obj) {
obj.name = "Lee";
obj = new Object();
obj.name = "jeungwoo";
return obj;
}
let person = new Object();
person = setName(person);
alert(person.name);
< /script>

이런 식으로 가능.

instance of

객체의 타입 확인.
a instanceof Object > true, false

Object 타입 추가 방법. 여러 객체 생성 방법.

< body>
< script>
var person1 = new Object();
person1.name = "simon";
person1.age = 29;

    var person2 = {
        name : "Nicol",
        age : 30
    };

    var person3 = {}; //new Object()와 동일
    person3.name = "paul";
    person3.age = 31;

    document.write(person1.name + ' : ' + person1.age + '<br/>');
    document.write(person2.name + ' : ' + person2.age + '<br/>');
    document.write(person3.name + ' : ' + person3.age + '<br/>');
< /script>

< /body>

객체 생성 심화

< body>
< script>
function displayInfo(args) {
var output = "";

        if (typeof args.name == "string") {
            output += "Name : " + args.name + "\n"
        }
        if (typeof args.age == "number") {
            output += "Age : " + args.age + "\n";
        }
        alert(output);
    }
    displayInfo({
        name : "이정우",
        age : 27
    });

    displayInfo({
        name : "이정우2"
    });
< /script>

< /body>

JS 배열 생성

< body>
< script>
var colors1 = new Array();
var colors2 = new Array(5);
var colors3 = new Array("red", "blue", "green");
var colors4 = Array(3); //new Array()와 동일. new keyword 생략 가능.

    //배열 리터널 표기법
    var colors5 = ["red", "blue", "green"];
    var colors6 = []; //빈 배열

    alert(colors5[0]);
    colors5[3] = "brown"; //길이가 4로 늘어남.
    alert(colors5.length);
< /script>

< /body>
JS에서 배열은 길이가 고정되어 있지 않다. 유동적으로 늘리거나 줄이기가 용이하다.

colors5.length = 4; 로 배열의 길이도 조절 가능. 만약 colors5가 길이가 5이고 원소로는 0, 1, 2, 3, 4를 갖는다고 치고 colors.length = 4로 해버리면 길이가 4로 고정되기에 배열은 0, 1, 2, 3만 남게 된다.4는 사라짐.

++ colors[colors.length] = anything; 이렇게 하면 배열의 길이를 1 늘리면서 새로운 값을 넣을 수 있다.

toFixed() 소수 자리수 제한

toFixed(n); n자리까지 반올림해서 소수점 자리 맞춰줌.

String 메서드

var input = "abcdefg 123";
alert(input.slice(3)); //"defg 123"
alert(input.substring(3)); //"defg 123"
alert(input.substr(3)); //"defg 123"
alert(input.slice(3, 7)); //"defg"
alert(input.substring(3, 7)); //"defg"
alert(input.substr(3, 7)); //"defg 12"

String 위치

var input = "hello world!";
alert(input.indexOf("e")); // 1 앞에서부터 찾기 시작
alert(input.lastIndexOf("o")); // 7 뒤에서부터 찾기 시작.

배열 값 추가

배열.push(값);

getElementById를 통해 값 css 변경하기.

document.getElementById("p1").style.color = "red";
document.getElementById("p1").style.fontFamily = "Century Schoolbook";
document.getElementById("p1").style.fontStyle = "italic";
함수로 지정해서 사용도 가능.

마우스 이벤트 (마우스 갖다 대면 발동)

< script>
function OnMouseIn(elem) {
elem.style.border = "2px solid red";
}
function OnMouseOut(elem) {
elem.style.border = "";
}
< /script>
< /head>
< body id="target">
< div style="background-color: yellow; width: 200px"
onmouseover="OnMouseIn(this)">
Mouse move in.
< /body>

여기서 this는 div

마우스 이벤트(클릭 한 상태)

< head>
< script>
function OnButtonDown(button) { //누르고 있으면
button.style.color = "#ff0000";
}
function OnButtonUp(button) { //누르고 있는걸 때면
button.style.color = "#00ff00";
}
< /script>
< /head>
< body>
< button
onmouseup="OnButtonUp(this)">Press!< /button>
< /body>

출처 : 국비 교육

profile
프로그래밍 공부 중!

0개의 댓글