Professional javascript for web Developers 2nd Edition 学习笔记(2)
- 引用数据类型
两种创建对象实例方法
- var person = new Object();
person.name = “Nicholas”;
person.age = 29; - var person = {
name : “Nicholas”,
age : 29
};
第二种为object literal notation,如果在29后加逗号(,)在ie7和opera中会出现错误
还有一种等同于第一种方法,虽然看起来会很奇怪
var person = {}; //same as new Object()
person.name = “Nicholas”;
person.age = 29;
我们偏向于第二种方法尤其是当传递大量数据的时候,例如
function displayInfo(args) {
var output = “”;
if (typeof args.name == “string”){
output += “Name: “ + args.name + “\n”;
}
if (typeof args.age == “number”) {
output += “Age: “ + args.age + “\n”;
}
alert(output);
}
displayInfo({
name: “Nicholas”,
age: 29
});
displayInfo({
name: “Greg”
});
引用对象的属性一般我们用.在ECMAScript中可以有下面几种方法
- alert(person[“name”]); //”Nicholas”
- var propertyName = “name”;
alert(person[propertyName]); //”Nicholas” - alert(person.name); //”Nicholas”
除非必要我们当然用第三种方法了。
- 数组类型
ECMAScript数组和其它大多数语言不同,允许第一个是字符串型,第二个是数值型,而第三个是对象,等等...
两种方法创建数组
- var colors = new Array();var colors = new Array(20);var colors = new Array(“red”, “blue”, “green”);
- var colors = [“red”, “blue”, “green”]; //creates an array with three strings
var names = []; //creates an empty array
var values = [1,2,]; //AVOID! Creates an array with 2 or 3 items
var options = [,,,,,]; //AVOID! creates an array with 5 or 6 items
第二种方法是array literal notation方法
考虑到兼容性,取得和设置数组数据可以用下面方法
var colors = [“red”, “blue”, “green”]; //define an array of strings
alert(colors[0]); //display the first item
colors[2] = “black”; //change the third item
colors[3] = “brown”; //add a fourth item
数组最大可以容纳4,294,967,295 items
posted on 2009-06-04 16:58 miaozi1123 阅读(299) 评论(0) 编辑 收藏 举报