1. 객체와 배열은 유사하다. 


배열은 인덱스로 접근하지만 객체는 키로 접근한다.


생성>

<script type="text/javascript">

var product = {

name : 'abcd',

type : 'bag',

made : 'korea'

}

</script>


객체요소접근방법>

  1. product['name'] --> 'abcd'
    product['type'] --> 'bag'
    ...
  2. product.name --> 'abcd'
    product.type --> 'bag'
    ...
; 식별자가 아닌 문자를 키로 사용할 경우는 [ ]를 사용한다. 
; product['made in'] 




2. 객체의 내부 값 --> 속성


name, type, made, ...  :  속성


객체의 속성 중 함수자료형인 경우를 메서드라고 한다.


예)

var person = {

name : '홍길동',

eat : function (food){ }

};


person.eat();





3. 객체 내 반복문 사용 시 for in 사용.


예)

<script type="text/javascript">

var product = {

name : 'abcd',

type : 'bag',

made : 'korea'

}

var output ='';

for(var key in product){

output += '* ' + key + ' : ' + product[key] + '\n';

}

alert(output);

</script>






4. in, with 


in

예)

<script type="text/javascript">

var student = {

name: 'mike',

kor : 100,

mat : 85,

eng : 90

}

var output ='';


output += "'name' in student: " + ('name' in student) + "\n";

output += "'sex' in student: " + ('sex' in student);

alert(output);

</script>



; name은 존재하기 때문에 true, sex은 없으므로 false.



with 

예)


<script type="text/javascript">

var student = {

name: 'mike',

kor : 100,

mat : 85,

eng : 90

}

var output ='';


output += "name: " + student.name + "\n";

output += "kor: " + student.kor + "\n";

output += "mat: " + student.mat + "\n";

output += "eng: " + student.eng + "\n";

alert(output);

</script>

를 


<script type="text/javascript">

var student = {

name: 'mike',

kor : 100,

mat : 85,

eng : 90

}

var output ='';


with(student){

output += "name: " + name + "\n";

output += "kor: " + kor + "\n";

output += "mat: " + mat + "\n";

output += "eng: " + eng + "\n";

}

alert(output);

</script>







5. 속성 추가 및 제거


예) 추가

<script type="text/javascript">

var student = {};

student.name ='홍길동';

student.kor =80;

student.eng =70;

student.mat =60;

</script>


예) 메서드 추가

<script type="text/javascript">

var student = {};

student.name ='홍길동';

student.kor =80;

student.eng =70;

student.mat =60;

student.sum = function(){

var output = 0;

for( var key in this ){

if( key != 'name' ){

output += this[key];

}

}

return output;

}

alert(parseInt(student.sum()));

</script>


예) 속성 제거

delete( student.kor);




+ Recent posts