Javascript_备忘录5

---恢复内容开始---

    今天看了Javascript的statement,看的不是很认真,所以今天就对操作符in和instanceof还有循环声明for/in进行备忘。

    对于in操作符,他的左操作数是string型或者可以转换为string的类型,他的右操作数是类类型。如果左操作数是右操作数的一个属性,那么该表达式值为true。例子:

var point = { x:1, y:1 }; // Define an object
"x" in point // => true: object has property named "x"
"z" in point // => false: object has no "z" property.
"toString" in point // => true: object inherits toString method

var data = [7,8,9]; // An array with elements 0, 1, and 2
"0" in data // => true: array has an element "0"
1 in data // => true: numbers are converted to strings
3 in data // => false: no element 3

    对于instanceof操作符,他的左操作数是一个对象,他的右操作数是类类型,如果左操作数是右操作数的一个实例,则表达式的值为true。例子:

var d = new Date(); // Create a new object with the Date() constructor
d instanceof Date; // Evaluates to true; d was created with Date()
d instanceof Object; // Evaluates to true; all objects are instances of Object
d instanceof Number; // Evaluates to false; d is not a Number object

var a = [1, 2, 3]; // Create an array with array literal syntax
a instanceof Array; // Evaluates to true; a is an array
a instanceof Object; // Evaluates to true; all arrays are objects
a instanceof RegExp; // Evaluates to false; arrays are not regular expressions

    对于for/in循环语句,他循环的是已经存在于内存中的属性和方法:

for (variable in object)
       statement

variable可以是一个表达式,他的值可以是变量,类的属性或者数组的元素,还可以直接通过var声明一个简单变量。object可以是一个返回对象的表达式。例如:

<script>
var Cat = function(){
      this.name = 'mitty';
      this.space = 'home';
      this.a;
var b;
} Cat.prototype = { getName : function(){ return this.name; }, setName : function(name){ this.name = name; } } var cat1 = new Cat; for (var test1 in cat1){ //利用var声明一个变量,输出的是name,space,getName,setName,所以我觉得他循环的只是类中已经初始化的属性和方法(也就是已经放入内存的东东)
alert(test1); }
for (cat1.a in cat1){ //利用类属性cat1.a,输出同上,但是会不断修改cat1.a alert(cat1.a); } alert(cat1.a); //输出setName var l = [1,2,3,4]; for (l[2] in cat1){ //利用数组元素,输出一样,但是会不断修改l[2] alert(l[2]); } </scrtpt>

我目前只知道该循环可以用来查找类中已经初始化或者已经在内存中的属性名和方法名,我试着用typeof来确定该输出值是什么类型,结果是string型。所以我们可以用条件语句来实现一些判断。由于自己代码看的少,例子也想不到。想到再补充了~~~

posted @ 2013-01-06 02:57  Key_Ky  阅读(167)  评论(0编辑  收藏  举报