Javascript学习笔记学习笔记-详解详解in运算符运算符
in运算符是javascript语言中比较特殊的一个,可以单独使用作为判断运算符,也常被用于for...in循环中遍历对象
属性
一、判断一、判断
语法
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;