深入理解JavaScript對象屬性
創(chuàng)建JavaScript的對象,可以通過對象.屬性名獲取值,也可以通過對象['key']
獲取內(nèi)容。
使用對象['key']
,傳入的內(nèi)容都會被轉(zhuǎn)換為字符串值。
var obj = { a: 'test', b: 'test2' }; obj.a; //test obj['b'];//test2
屬性讀寫
var obj = { a: 'test', b: 'test2' }; obj.a; //test obj['b'];//test2
屬性異常
如果讀取沒有的屬性,通常會返回undefined,如果二維值的話,會報錯。
console.log(obj.z);//undefined console.log(obj.z.b);//Uncaught TypeError: Cannot read property 'b' of undefined obj.y.z = 2; // TypeError: Cannot set property 'z' of undefined //可以通過判斷是否存在 if (obj.y) { //存在的話則執(zhí)行 }
屬性枚舉
var key; for (key in obj) { console.log(obj[key]); }
屬性刪除
使用delete關(guān)鍵字
delete obj.a;//true obj.a; // undefined
如果這個屬性設(shè)置過configurable為true,則不能刪除。
默認創(chuàng)建的屬性,configurable為false。下面講如何設(shè)置為true。
不能刪除全局變量
var globalVal = 1; delete globalVal; // false
不能刪除函數(shù)
function fd() {} delete fd; // false
可以刪除Window上的變量
ohNo = 1; window.ohNo; // 1 delete ohNo; // true
屬性檢測
判斷是否存在這個屬性
var obj = { a: 'test', b: 'test2' }; 'a' in obj;//true 'toString' in obj //true
在原型鏈上的值也可以被檢測到。
例如所有對象上都有toString屬性.
每個屬性都有一個屬性:enumerable,是否可以被檢測,默認為true,如果為false,則檢測不到這個屬性,不能遍歷。
var obj = { a: 'test', b: 'test2' }; Object.defineProperty(obj, 'price', { enumerable: false, value: 1000 }); var key; for (key in obj) { console.log(obj[key]) } //只輸出test和test2
判斷這個屬性可否被枚舉,true 可以,false不能
obj.propertyIsEnumerable('price');
設(shè)置屬性的屬性
版權(quán)聲明:
作者:applek
鏈接:http://m.aaigroup.cn/srljjsdxsx.html
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載。
THE END