ECMAScript是一門面向對象的語言俊扭,描述的是一類對象所具有的屬性和方法翰舌。
-
==Object類型==
創(chuàng)建方法
-
使用new關鍵字(構造函數(shù))
var person = new Object(); person.name = "lili"; person.age = 18;
-
使用對象字面量
var person = { //{ 表示一個表達式的開始 name: "lili", //是逗號 age: 18 //對象的最后一個屬性添加逗號會在IE7及更早的瀏覽器版本和Opera中導致錯誤 } //} 表示一個表達式的結束
對象字面量的屬性名也可以使用字符串巷懈,比如:
var person = { "name": "lili", "age": 18 }
訪問對象
-
點表示法
alert(person.name);
-
方括號法
alert(person["name"]);
? 方括號可以使用變量訪問(主要優(yōu)點):
var propertyName = "name"; alert(person[propertyName]);
? 如果屬性名中包含:導致語法錯誤的字符(比如空格)顶燕,使用的是關鍵字或保留字冈爹,包含非字母和非數(shù)字的(屬性名是可以包含的)。也需要使用方括號法:
person["first name"] = "lili"; //空格恳谎,不能使用點表示法訪問
-
-
==Array類型==
創(chuàng)建方法
-
使用Array構造函數(shù)
var colors = new Array(); var colors = new Array(20); //20表示數(shù)組的長度:length=20 var colors = new Array("red"); //創(chuàng)建一個包含一項的數(shù)組 var colors = Array(3); //省略new與上面結果相同 var colors = Array("red"); //省略new與上面結果相同
-
使用數(shù)組字面量
var colors = ["red", "blue"]; //中間用逗號因痛,末尾沒有符號 var names = []; //創(chuàng)建一個空數(shù)組 var values = [1, 2,]; //不要這樣鸵膏!會創(chuàng)建一個包含2或3項的數(shù)組length=2||3(IE8-) var options = [,,,,,]; //不要這樣怎炊!會創(chuàng)建一個包含5或6項的數(shù)組length=5||6(IE8-)
訪問數(shù)組
? 使用方括號并使用相應值得基于==0==的數(shù)字索引
var colors = ["red", "blue", "green"]; alert(colors[0]); //red colors[2] = "orange"; //修改第三項"green"=>"orange" colors[3] = "gray"; //新增第四項"gray"
? 數(shù)組的長度length,不是只讀的债查≡愀郏可以通過它添加刪除元素
var colors = ["red", "blue", "green"]; colors.length = 2; alert(colors[2]); //underfined colors[colors.length] = "pink"; alert(colors[2]); //pink colors.length = 4; alert(colors[3]); //underfined
檢測數(shù)組
? 檢測某個對象是不是數(shù)組(比如document.getElementsByClassName(“demo”);得到就是偽數(shù)組)
if (value instanceof Array) { //instanceof:實例 //對數(shù)組執(zhí)行某些操作 }
? 也可以使用Array.isArray()方法---ECMA5新增
if (Array.isArray(value)) { //對數(shù)組執(zhí)行某些操作 }
-