[英]Finding object keys in Javascript
我正在研究ExtJS webapp,並且正在尋找一種方法來列出所有對象自己的屬性名稱。 谷歌搜索,我很快在這個博客上找到了一些參考代碼。 現在,當使用這個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
嘗試檢查hasOwnProperty
以僅列出數組本身的屬性,而不是其原型。
for (var i in keys(test)) {
if(keys(test).hasOwnProperty(i)){
console.log(i);
}
}
是的,正如@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>');
keys(test)
返回一個數組,因此你應該使用經典的for-init-condition-next loopm而不是for-in循環。
(function(arr) {
for (var i = 0; i < arr.length; i ++) {
console.log(i);
}
})(keys(test));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.