我正在研究ExtJS webapp,并且正在寻找一种方法来列出所有对象自己的属性名称.谷歌搜索,我很快在
this blog上找到了一些参考代码.现在,当使用这个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
解决方法
是的,正如@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: "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>');