您的位置:首页 > 移动开发 > Objective-C

[JavaScript] Access the properties of an object

2011-09-04 13:36 603 查看

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" 
							onclick="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

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐