Finding Object Keys in Javascript

I am working on extJS webapp and was looking for a way to list all the names of my own objects. Google, I quickly found the link code for this blog . Now, when using this keys () method, I find strange behavior when listing property names of object objects. Code example:

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); } 

When you run this code, the console displays:

 0 1 2 remove() 

Thus, the "remove ()" function is also displayed at the top of the expected property names 3. This is clearly related to ExtJS because the enumeration works as expected on an empty download page other than ExtJS.

Can someone explain to me exactly what ExtJS is doing here? Is there a better way to list property names of an object-object?

Thanks wwwald

+6
source share
3 answers

Yes, as @Thai said, do not use for..in, since any array is an object and could potentially have different additions in different frameworks.

 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>'); 
+3
source

Try checking hasOwnProperty only to display the properties of the array itself, not its prototype.

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

keys(test) returns an array, so you should use the classic for-init-condition-next loop, not the for-in loop.

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

Source: https://habr.com/ru/post/888035/


All Articles