javascript - Whats the proper way to iterate through an object? -


i've used

for( x in object ){} 

but came accros

for( var x in object){} 

i know var matters in regular

for( var i=0;i<10;i++){} 

statements, bit me once in recursive function, matter when using x in?...

re var part:

does matter when using x in?

yes. always matters declare variables. if don't, , you're using loose mode, fall prey the horror of implicit globals. (in strict mode, it's nice detectable error. use strict mode.) bite in recursive function, , in of large number of other non-recursive situations.

you don't have declare within for construct, make sure declare somewhere.


re "whats proper way iterate through object?":

there several proper ways. like mathletics, i'm partial using object.keys(...).foreach(...):

var obj = {    a: "ay",    b: "bee",    c: "see"  };  object.keys(obj).foreach(function(key) {    snippet.log(key + ": " + obj[key]);  });
<!-- script provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->  <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

note object.keys @ object's own properties, not properties of prototype.

the reason gives me nice self-contained scope i'm doing on each "loop" iteration. if you're worried runtime cost of callbacks, don't be.


but can use for in loop. if do, may or may not want include hasownproperty, depending on whether want visit prototype properties.

var proto = {    a: "ay (proto)",    b: "bee (proto)",    c: "see (proto)",    d: "dee (proto)"  };  var obj = object.create(proto);  obj.a = "ay";  obj.b = "bee";  obj.c = "see";    // includes prototype properties if not shadowed object's own  snippet.log("for-in without hasownproperty");  var key;  (key in obj) {    snippet.log(key + ": " + obj[key]);  }    // not include prototype properties  snippet.log("for-in using obj.hasownproperty");  (key in obj) {    if (obj.hasownproperty(key)) {      snippet.log(key + ": " + obj[key]);    }  }    // if you're feeling paranoid `obj` having had  // `hasownproperty` overridden, can use `object.prototype`:  snippet.log("for-in using object.prototype.hasownproperty");  (key in obj) {    // not include prototype properties    if (object.prototype.hasownproperty.call(obj, key)) {      snippet.log(key + ": " + obj[key]);    }  }  // i've never needed in real world, though
<!-- script provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->  <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

just don't use for-in on arrays without using appropriate safeguards; more why (and alternatives) in this answer.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -