欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Javascript學習筆記-詳解in運算符

 更新時間:2011年09月13日 21:57:35   作者:  
in運算符是javascript語言中比較特殊的一個,可以單獨使用作為判斷運算符,也常被用于for...in循環(huán)中遍歷對象屬性
一、判斷
語法
prop in objectName
如果objectName指向的對象中含有prop這個屬性或者鍵值,in運算符會返回true。
復制代碼 代碼如下:

var arr = ['one','two','three','four'];
arr.five = '5';
0 in arr;//true
'one' in arr; //false,只可判斷數(shù)組的鍵值
'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循環(huán)語句,此語句中的in需要遵循另外一套語法規(guī)范:

for (variable in object)
statement
與單獨使用in作為運算符不同,for...in循環(huán)語句只遍歷用戶自定義的屬性,包括原型鏈上的自定義屬性,而不會遍歷內置(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對象,經(jīng)過測試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'
}

字面量
遍歷數(shù)組字面量的鍵值和屬性
復制代碼 代碼如下:

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雖然有這方面的規(guī)范,但瀏覽器之間還是存在著差異,鑒于此,并不推薦用for...in去遍歷字符串,也不推薦拿去遍歷數(shù)組(如例子所示,為數(shù)組加上自定義屬性,遍歷就會被搞亂)

在遍歷對象方面,我們還可以使用對象的內置方法hasOwnProperty()排除原型鏈上的屬性,進一步加快遍歷速度,提升性能
復制代碼 代碼如下:

function each( object, callback, args ){
var prop;
for( prop in object ){
if( object.hasOwnProperty( i ) ){
callback.apply( prop, args );
}
}
}

相關文章

最新評論