网络编程
位置:首页>> 网络编程>> JavaScript>> 如何编写高质量的Javascript代码(5)

如何编写高质量的Javascript代码(5)

 来源:rockux 发布时间:2011-03-07 16:04:00 

标签:javascript,代码,经验

for-in循环

for-in循环用来迭代非数组的对象。使用for-in循环通常也成为枚举。

从技术上来说,你也可以用for-in来循环数组,因为数组也是对象,但是不推荐。如果数组有一些自定义的扩展函数,那么就会出错。另外,对象属性的顺序在for-in循环中也是不确定的。所以最好还是用普通的循环来循环数组用for-in来循环对象。

在循环对象的过程中,使用hasOwnProperty()方法来检验是对象本身的属性还是原型链上的属性很重要。

看看下面的这个例子。




// the object
var man = {
   hands: 2,
   legs: 2,
   heads: 1
}; 
 
// somewhere else in the code
// a method was added to all objects
if (typeof Object.prototype.clone === "undefined") {
   Object.prototype.clone = function () {};
}

在这个例子中,我们有一个简单的称作man的对象字面量。在其他man定义之前或之后的地方,对象原型有一个很有用的clone()方法。因为原型链的原因,所有的对象都自动获得了这个方法。为了在枚举man对象的时候出现clone方法,你需要使用hasOwnProperty方法来区别。如果没有区别来自原型链的方法,那么就会有一些意想不到的事情发生:




// 1.
// for-in loop
for (var i in man) {
   if (man.hasOwnProperty(i)) { // filter
      console.log(i, ":", man[i]);
   }
}
/* result in the console
hands : 2
legs : 2
heads : 1
*/
// 2.
// antipattern:
// for-in loop without checking hasOwnProperty()
for (var i in man) {
   console.log(i, ":", man[i]);
}
/*
result in the console
hands : 2
legs : 2
heads : 1
clone: function()
*/

 

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com