JavaScript/생활코딩

WEB2 - JavaScript - 객체예고, 객체

점미 2019. 1. 2. 15:13



객체예고 - https://opentutorials.org/course/3085/18884

객체 - https://opentutorials.org/course/3085/18853



객체 쓰기와 읽기


<html>

<body>

<script>

var coworkers = {

"programmer":"egoing",

"designer":"leezche"

};  //coworkers 변수에 이름-값이 있는 객체를 담는다.


document.write("programmer : "+coworkers.programmer+"<br>"); //화면에 출력하기 위해 객체를 가져온다.

document.write("designer : "+coworkers.designer+"<br>");

coworkers.bookeeper = "duru"; //중간에 객체에 이름-값을 추가하는 방법이다.

document.write("bookeeper : "+coworkers.bookeeper+"<br>");


coworkers["data scientist"] = "taeho"; //객체의 이름에 띄어뜨기가 들어갔을 때 추가하는 방법이다.

document.write("data scientist : "+coworkers["data scientist"]+"<br>");

</script>

</body>

</html>


[결과화면]







객체와 반복문


생성된 객체에 어떤 데이터가 있는지 모두 가져오는 방법


<html>

<body>

<script>

var coworkers = {

"programmer":"egoing",

"designer":"leezche"

};

document.write("programmer : "+coworkers.programmer+"<br>");

document.write("designer : "+coworkers.designer+"<br>");

coworkers.bookeeper = "duru";

document.write("bookeeper : "+coworkers.bookeeper+"<br>");

coworkers["data scientist"] = "taeho";

document.write("data scientist : "+coworkers["data scientist"]+"<br>");

</script>

<h2>Iterate</h2>

<script>

//key값은 객체의 이름-값에서 이름부분이다. coworkers객체 있는 객체들의 수만큼 반복되는데 key값들을 변수들로 다 불러온다.

for(var key in coworkers){ 

document.write(key+"<br>"); //key값을 호출해보면 객체들의 이름이 나열된다.

document.write(coworkers[key]+"<br>"); //coworkers[key]을 활용하여 객체들의 값들이 나열된다.

document.write("<br>");

}

</script>

</body>

</html>


[결과화면]










프로퍼티와 메소드



<html>

<body>

<script>

var coworkers = {

"programmer":"egoing",

"designer":"leezche"

};

document.write("programmer : "+coworkers.programmer+"<br>");

document.write("designer : "+coworkers.designer+"<br>");

coworkers.bookeeper = "duru";

document.write("bookeeper : "+coworkers.bookeeper+"<br>");

coworkers["data scientist"] = "taeho";

document.write("data scientist : "+coworkers["data scientist"]+"<br>");

</script>

<h2>Iterate</h2>

<script>

for(var key in coworkers){ //key값은 객체의 이름-값에서 이름부분이다. coworkers객체 있는 객체들의 수만큼 반복되는데 key값들을 변수들로 다 불러온다.

document.write(key+"<br>");

document.write(coworkers[key]+"<br>");

document.write("<br>");

}

</script>

<h2>Property & Method</h2>

<script>

//function showAll{} 와 같은 의미이다.

coworkers.showAll = function(){

for(var key in coworkers){

document.write(key+"<br>");

document.write(this[key]+"<br>");

document.write("<br>");

}

}

coworkers.showAll();   //객체에 함수를 정의하고, 객체의 함수(메소드)를 호출할 수 있다.

</script>

</body>

</html>



댓글수0