DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> Javascript學習筆記-詳解in運算符
Javascript學習筆記-詳解in運算符
編輯:關於JavaScript     
一、判斷
語法
prop in objectName
如果objectName指向的對象中含有prop這個屬性或者鍵值,in運算符會返回true。
復制代碼 代碼如下:
var arr = ['one','two','three','four'];
arr.five = '5';
0 in arr;//true
'one' in arr; //false,只可判斷數組的鍵值
'five' in arr;//true,'five'是arr對象的屬性
'length' in arr;//true

原型鏈
in運算符會在整個原型鏈上查詢給定的prop屬性
復制代碼 代碼如下:
Object.prototype.sayHello = 'hello,world';
var foo = new Object();
'sayHello' in foo;//true;
'toString' in foo;//true;
'hasOwnProperty' in foo;//true;

對象與字面量
in運算符在對待某些特定類型(String,Number)的對象和字面量時顯得不盡相同
復制代碼 代碼如下:
var sayHelloObj = new String('hello,world');
var sayHello = 'hello,world';
var numObj = new Number(1);
var num = 1;

'toString' in sayHelloObj; //true
'toString' in sayHello; //類型錯誤

'toString' in numObj;//true
'toString' in num;//類型錯誤

究其原因,在MDN找到這樣一段關於String對象和字面量轉換的介紹,似乎可以解釋這個原因:


Because JavaScript automatically converts between string primitives and String objects, you can call any of the methods of the String object on a string primitive. JavaScript automatically converts the string primitive to a temporary String object, calls the method, then discards the temporary String object. For example, you can use the String.length property on a string primitive created from a string literal
試著這樣理解:因為in是運算符而非一個方法(method),所以無法讓string字面量自動轉換成String對象,又因為in運算符待查詢方不是對象而是一個字符串(按老道Douglas的說法,只是object-like的類型),所以報類型錯誤。

二、遍歷

很常用到的for...in循環語句,此語句中的in需要遵循另外一套語法規范:

for (variable in object)
statement
與單獨使用in作為運算符不同,for...in循環語句只遍歷用戶自定義的屬性,包括原型鏈上的自定義屬性,而不會遍歷內置(build-in)的屬性,如toString。

對象
復制代碼 代碼如下:
function Bird(){
this.wings = 2;
this.feet = 4;
this.flyable = true;
}
var chicken = new Bird();
chicken.flyable = false;
for(var p in chicken){
alert('chicken.' + p + '=' + chicken[p]);
}

String對象,經過測試Firefox,Chrome,Opera,Safari浏覽器都是給出了注釋中的結果,只有IE浏覽器只給出'more'和'world'
復制代碼 代碼如下:
var str = new String('hello');
str.more = 'world';
for(var p in str){
alert(p);//'more',0,1,2,3,4
alert(str[p]);//'world','h','e','l','l','o'
}

字面量
遍歷數組字面量的鍵值和屬性
復制代碼 代碼如下:
var arr = ['one','two','three','four'];
arr.five = 'five';
for(var p in arr){
alert(arr[p]);//'one','two','three','four','five'
}

遍歷string字面量,雖說單獨在string字面量前面使用in運算符會報類型錯誤,不過下面的代碼卻能夠正常運行,此時IE浏覽器是毫無聲息
復制代碼 代碼如下:
var str = 'hello';
str.more = 'world';
for(var p in str){
alert(p);//0,1,2,3,4
alert(str[p]);//'h','e','l','l','o'
}

綜上
ECMA雖然有這方面的規范,但浏覽器之間還是存在著差異,鑒於此,並不推薦用for...in去遍歷字符串,也不推薦拿去遍歷數組(如例子所示,為數組加上自定義屬性,遍歷就會被搞亂)

在遍歷對象方面,我們還可以使用對象的內置方法hasOwnProperty()排除原型鏈上的屬性,進一步加快遍歷速度,提升性能
復制代碼 代碼如下:
function each( object, callback, args ){
var prop;
for( prop in object ){
if( object.hasOwnProperty( i ) ){
callback.apply( prop, args );
}
}
}
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved