The for..of
is a new construction in Ecmascript 6, and therefore should only be used when the browsers provide appropriate support for this version, and enable it by default. Otherwise, your code may be rejected by a significant portion of your users.
The for..of
is similar to for..in
, except that it only iterates on the properties enumerable of the object/array. A for..in
iterate over all of them, including custom properties added by the user:
function log(x) { document.body.innerHTML += "<pre>" + x + "<pre>"; }
var arr = [1,2,3];
arr.foo = "bar";
var obj = { 0:1, 1:2, 2:3, length:3, foo:"bar" };
var obj2 = Object.create(null, {
0: { value:1, enumerable:true },
1: { value:2, enumerable:true },
2: { value:3, enumerable:true },
length: { value:3 },
foo:{ value:"bar" }
});
document.body.innerHTML += "<h1>for..in</h1>";
for ( var p in arr ) {
log("arr[" + p + "] = " + arr[p]);
}
for ( var p in obj ) {
log("obj[" + p + "] = " + obj[p]);
}
for ( var p in obj2 ) {
log("obj2[" + p + "] = " + obj2[p]);
}
document.body.innerHTML += "<h1>for..of (simulação)</h1>";
arr.forEach(function(e, i) {
log("arr[" + i + "] = " + e);
});
arr.forEach.call(obj, function(e, i) {
log("obj[" + i + "] = " + e);
});
arr.forEach.call(obj2, function(e, i) {
log("obj2[" + i + "] = " + e);
});
In the example above, I used the Array.prototype.forEach
to simulate a for..of
- otherwise the example would not compile at all browsers, and according to MDN the behavior of both should be the same. It is also noted that the for..of
applies both to arrays and to "array-Likes", so that it can be used even in a list of DOM nodes (returned by document.querySelectorAll
for example).
P.S. As pointed out in too answers, there is also the difference that the variable used in the for..in
receives the name of the property, while in the for..of
she gets her value:
for ( var p in [1,2,3] ) // p será "0", "1", "2"
for ( var p of [1,2,3] ) // p será 1, 2, 3
The consequence of this is that, as far as I know, if you want to also refer to the index it is still necessary to use forEach
(but as in practice we are usually only interested in value, it is still a very useful construction).
Almost the same text, with 10s difference hehehe. Good answer!
– Caputo