인생은 여행 人生は旅

WEB - JavaScript(객체와 반복문) 본문

코딩 공부

WEB - JavaScript(객체와 반복문)

하늘빛 칵테일 2024. 1. 19. 10:47

coworkes(객체)의 어떤 특정한 데이터를 가져올 때 배열의 형식을 사용해서,

index 가 들어가는 곳에 key 값을 넣었더니 데이터를 가져올 수 있었다. 

[ 객체의 데이터를 순회하는 방법 ]

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Obeject</h1>
<h2>Create</h2>
<script>
var coworkers = {
"programmer" : "egoing" ,
"designer" : "leezche"
};
document.write("programmer : "+coworkers.programmer+"<br>");
document.write("designer : "+coworkers.designer+"<br>");
coworkers.bookkeeper = "duru";
document.write("bookkeeper : "+coworkers.bookkeeper+"<br>");
coworkers["data scientist"] = "taeho";;
document.write("data scientist : "+coworkers["data scientist"]+"<br>");
</script>
<h2>Iterate</h2>
<script>
for(var key in coworkers){
document.write(key+':'+coworkers[key]+'<br>');
}
</script>
</body>
</html>

 

 

 

 

객체에는 함수도 담을 수 있다.

Method : 객체에 소속된 함수

Property : 객체에 소속된 변수

<body>
<h1>Obeject</h1>
<h2>Create</h2>
<script>
var coworkers = {
"programmer" : "egoing" ,
"designer" : "leezche"
};
document.write("programmer : "+coworkers.programmer+"<br>");
document.write("designer : "+coworkers.designer+"<br>");
coworkers.bookkeeper = "duru";
document.write("bookkeeper : "+coworkers.bookkeeper+"<br>");
coworkers["data scientist"] = "taeho";;
document.write("data scientist : "+coworkers["data scientist"]+"<br>");
</script>
<h2>Property & Method</h2>
<script>
for(var key in coworkers){
document.write(key+':'+coworkers[key]+'<br>');
}
</script>
<h3>Property & Method</h3>
<script>
coworkers.showAll = function(){
for(var key in coworkers){
document.write(key+':'+coworkers[key]+'<br>');
}
}
coworkers.showAll();
 
</script>
</body>

 

coworkers 대신에 자기 자신을 가리키는 this로 변경해 주면 coworkers라는 변수의

이름이 바뀌어도 영향을 받지 않는다.

<h3>Property & Method</h3>
<script>
coworkers.showAll = function(){
for(var key in this){
document.write(key+':'+this[key]+'<br>');
}
}
coworkers.showAll();
 
</script>

 

처음이라 이해가 되지 않는 게 정상이라고 

마음 편하게 들으라고 하시는데 마음이 

불편해집니다 ㅎㅎㅎ

'코딩 공부' 카테고리의 다른 글

WEB - Python 실습환경 준비(Code Anywhere & Python설치)  (1) 2024.01.23
WEB - Python 소개  (0) 2024.01.22
WEB2 - JavaScript(객체)  (0) 2024.01.18
WEB2 -JavaScript(함수활용)  (0) 2024.01.17
WEB2 - JavaScript(함수)  (0) 2024.01.16