1. object does not have the property of length, so if you need to iterate properties of the object, you can only
<html>
<head>
<script type="text/javascript">
function iterateObjectProperty() {
var homer = {"name": "Homer Simpson",
"age": 34,
"married": true,
"occupation": "plant operator",
'email': "homer@example.com",
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"
οnclick="iterateObjectProperty();"/>
</form>
</body>
</html>
2. To access the properties of an object, you can
object.property // the property name is an identifier, customer.("address" + i),error
object[“property”] // the property name is a string, customer["address" + i],OK
When you use the . operator to access a property of an object, however, the name of the property is expressed as an identifier. Identifiers must be typed literally into your JavaScript program; they are not a datatype, so they cannot be manipulated by the program. The following code is illegal:
var addr = ""; for(i = 0; i < 4; i++) { addr += customer.("address" + i) + '\n'; //error } |
On the other hand, when you access a property of an object with the [] array notation, the name of the property is expressed as a string. Strings are JavaScript datatypes, so they can be manipulated and created while a program is running. The following code is legal:
var addr = ""; for(i = 0; i < 4; i++) { addr += customer["address" + i] + '\n';// OK } |