JavaScript的in操作符可以用來判斷一個屬性是否屬於一個物件,也可以用來變數一個物件的屬性
1. 判斷屬性屬於物件
var mycar = {make: "Honda", model: "Accord", year: 1998}; //注意,屬性名必須是字串形式,因為make不是一個變數 if ( "make" in mycar ){ document.write('true'); } else{ document.write('false'); // 顯示true }
2. for in遍歷物件屬性
var mycar = {make: "Honda", model: "Accord", year: 1998}; for(var p in mycar){ console.log(p + ': ' + make[p]); }
3. in可以用來進行判斷
if ( foo == 'bar' || foo == 'foobar' || foo == 'foo' ) { //... } //就可以寫成: if ( foo in { 'bar':'', 'foobar':'', 'foo':'' } ) { //... }
4. delete操作符可以刪除屬性,配合in使用
var mycar = {make: "Honda", model: "Accord", year: 1998}; delete mycar.make; "make" in mycar; // returns false var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); delete trees[3]; 3 in trees; // returns false
5. 儘量不要用for in遍歷陣列
集合遍歷的效率為:hash > for(;;) > for(in)
集合相關操作首選物件,次之用for迴圈遍歷。
參考:http://www.linuxfly.org/post/524/