Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Đối tượng trong JavaScript và cách truy cập thuộc tính


Truy cập thuộc tính Object

Mọi thứ trong JS (boolean, number, function...) đều là object. Truy cập thuộc tính bằng dấu chấm (.) hoặc ngoặc vuông ([]).

Ví dụ 1: Truy cập thuộc tính lồng nhau

<html> <body> <script> myObj = {"name":"Ramesh","age":30,"family": [{"mother":"Geetha","father":"Rao"}],"city":"Berlin"}; var res = myObj.family[0].mother; document.write(res); </script> </body> </html>

Kết quả

Geetha

Ví dụ 2: Truy cập thuộc tính đơn giản

<html> <body> <script> myObj = {"name":"Ramesh","age":30,"family": [{"mother":"Geetha","father":"Rao"}],"city":"Berlin"}; var res = myObj.city; document.write(res); </script> </body> </html>

Kết quả

Berlin