[JavaScript]Access the properties of an object
2070 ワード
1. object does not have the property of length、so if you need to iterate properties of the object、you can only
object.property //the property name is an identifer、 customer.("address"+i)、error
object[property] //the property name is a ストリングス customer["address"+i]OK
When you use the.operato access a property of an object,however,the name of the property is expresed as an identifer.Identifers must be typed literally into your JavaScript program;they are not a datatype,so they cannot be manipulated by the program.The follwing code is illegal:
var addr="for(i=0;i<4;i+){ addr+= customer.(「address」+i) + '';//error
On the other hand,when you access a property of an object with the[]array notation,the name of the property is expresed as a string.Strigs are JavaScript datatypes,so they can be maipulated and created while a program is running.The follwing code is legal:
var addr="for(i=0;i<4;i+){ addr+= customer["address"+i] + '';// OK}
<html>
<head>
<script type="text/javascript">
function iterateObjectProperty() {
var homer = {"name": "Homer Simpson",
"age": 34,
"married": true,
"occupation": "plant operator",
'email': "[email protected]",
x: 1,
y: '2'
};
var displayValue = '';
var tmp = '';
for(tmp in homer){
displayValue += tmp +": "+ homer[tmp]+", ";
}
alert(displayValue);
}
</script>
</head>
<body>
<form>
<input type="button" name="demojavascript" value="Demo Iterate Object Property"
onclick="iterateObjectProperty();"/>
</form>
</body>
</html>
2. To access the properties of an object,you canobject.property //the property name is an identifer、 customer.("address"+i)、error
object[property] //the property name is a ストリングス customer["address"+i]OK
When you use the.operato access a property of an object,however,the name of the property is expresed as an identifer.Identifers must be typed literally into your JavaScript program;they are not a datatype,so they cannot be manipulated by the program.The follwing code is illegal:
var addr="for(i=0;i<4;i+){ addr+= customer.(「address」+i) + '';//error
On the other hand,when you access a property of an object with the[]array notation,the name of the property is expresed as a string.Strigs are JavaScript datatypes,so they can be maipulated and created while a program is running.The follwing code is legal:
var addr="for(i=0;i<4;i+){ addr+= customer["address"+i] + '';// OK}