在Javascript中查找对象键

6

我正在开发一个ExtJS Web应用程序,想要列出对象的所有属性名称。通过搜索,我很快在这个博客上找到了一些参考代码。现在,在使用这个keys()方法时,当枚举对象中的对象的属性名称时,我发现一些奇怪的行为。示例代码:

keys = function(obj) {
    if (typeof obj != "object" && typeof obj != "function" || obj == null) {
        throw TypeError("Object.keys called on non-object");
    }
    var keys = [];
    for (var p in obj) 
        obj.hasOwnProperty(p) && keys.push(p);
    return keys;
};

var test = {}
test["nr1"] = {testid: 1, teststr: "one"};
test["nr2"] = {testid: 2, teststr: "two"};
test["nr3"] = {testid: 3, teststr: "three"};
for (var i in keys(test)) {
    console.log(i);
}

运行此代码时,控制台输出:
0
1
2
remove()

所以,在期望的3个属性名称之上,它还列出了一个“remove()”函数。这显然与ExtJS有关,因为在空白的、非ExtJS加载页面上,枚举按预期工作。

有人能解释一下ExtJS在这里到底做了什么吗?是否有更好的方法来枚举对象自有属性名称?

非常感谢, wwwald


7
ExtJS似乎已经向数组原型添加了一个函数。 - Liviu T.
3个回答

4

尝试检查hasOwnProperty,以仅列出数组本身的属性,而不是其原型。

for (var i in keys(test)) {
    if(keys(test).hasOwnProperty(i)){
      console.log(i);
    }
}

3

是的,正如@Thai所说,不要使用for..in,因为任何数组都是一个对象,可能在不同的框架中有不同的添加。

keys = function(obj) {
    if (typeof obj != "object" && typeof obj != "function" || obj == null) {
        throw TypeError("Object.keys called on non-object");
    }
    var keys = [];
    for (var p in obj) 
        obj.hasOwnProperty(p) && keys.push(p);
    return keys;
};

var test = {}
test["nr1"] = {testid: 1, teststr: "one"};
test["nr2"] = {testid: 2, teststr: "two"};
test["nr3"] = {testid: 3, teststr: "three"};
document.writeln('<pre>');
document.writeln('Current method');
for (var key in keys(test)) {
    document.writeln(key);
}


document.writeln('Better method1');
for (var arr=keys(test), i = 0, iMax = arr.length; i < iMax; i++) {
    document.writeln(arr[i]);
}

document.writeln('Better method2');
Ext.each(keys(test), function(key) {
   document.writeln(key); 
});
document.writeln('</pre>');

啊,我明白了。谢谢指出区别。Ext.each() 的解决方案似乎很完美! - wwwald

1

keys(test) 返回一个数组,因此您应该使用经典的 for-init-condition-next 循环,而不是 for-in 循环。

(function(arr) {
    for (var i = 0; i < arr.length; i ++) {
        console.log(i);
    }
})(keys(test));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接