Meta
VILIC20:04 - 12.27 2010
JavaScript for...in 语句的最佳用法( 2 responses )
Tags: ,

大家对JavaScript里的for...in语句一定不陌生吧, 不过, 这个语句有时会做一些我们可能不想它做的事. 比如:

Object.prototype.test = function () { };

var obj = {
    a: "aaa",
    b: "bbb"
};

//需要说明的一点是, 这里的i类型为string, 即使是对于数组, 也同样如此.
for (i in obj)
    alert(obj[i]);

结果发现test方法也跑出来. 为了避免这样的情况, 我们通常做简单的处理:

for (i in obj)
    if (typeof obj[i] != "function") 
        alert(obj[i]);

不过如果枚举的类型里也有function呢? 所以, 提出我认为的最佳方案:

for (i in obj)
    if (obj.constructor.prototype[i] === undefined)
        alert(obj[i]);

Original link of this archive: http://www.vilic.info/blog/archives/613
本文的原始链接: http://www.vilic.info/blog/archives/613

There're 2 Comments to "JavaScript for...in 语句的最佳用法"
  • wait09:26 - 01.06 2011
    对象有一个 hasOwnProperty 方法  可以帮你直接实现这个东西
    wait
  • Vilic14:07 - 01.06 2011
    @wait 啊, 有道理~ 谢了Wait~
    Vilic
Leave a Comment