27. 10. 2010

Javascript : for each...in vs for...in

I am new to javascript, so I just dig around, playing with jsfiddle.net, firebug, chrome developer tools, jQuery..etc. Recently I found out that there is for each (var value in object) statement. I only knew about for ( var value in object ) statement which I wrongly considered as a "true" foreach as I know it from Java or C# (C#'s foreach value in Iterableor Java's for value : Iterable). The difference is that for each in iterate over values of object properties (so it's like foreach in c# or for : in Java) when for in iterates only over property names (so it returns only String values and you can use this names to access property values this way var property_value = object [ property_name] ). Example:

var obj = {

function1: function() {},
function2: function() { return "return from function2"; },  
value1: "this is value1"
}

console.log("for each in:");
/* iterate over obj property values */  
for each (var value in obj) {
console.log(value);  
}
/* after this in your console (eg. in firebug) should be logged these:
function(), function(), "this is value1" - notice these are objects */ 

console.log("for in:");
/* iterate over property names in obj*/
for (var property in obj) { /* property variable is always String */
console.log(property); 
}
/* in your eg. firebug console there are logged these Strings: "function1", "function2", "value1" */




See: https://developer.mozilla.org/en/JavaScript/Reference/Statements/for_each...in

Žádné komentáře:

Okomentovat