JavaScript for every implementation

I found the code snippet for the forEach on the tutorial website, and everything makes sense to me, except for the line that checks if i in the array:

  if (i in this) { 

Why bother if we already have a for loop that has a stop condition?

 if (!Array.prototype.forEach) { Array.prototype.forEach = function(fun /*, thisp*/) { var len = this.length >>> 0; if (typeof fun != "function") { throw new TypeError(); } var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { fun.call(thisp, this[i], i, this); } } }; } 
+6
source share
2 answers

Two reasons:

1. Mutation callback

Calling fun can change the array, since fun completely user-defined. So you need to check again.

Example:

 array.forEach(function (el, i) { delete array[i + 1]; }); 

2. Rare arrays

Another problem is that there may be sparse arrays: for example,

 3 in ["a", "b", "c", , "e", "f"] === false // even though 3 in ["a", "b", "c", undefined, "e", "f"] === true 

In these cases, you do not want to call fun for this index / element, since there is nothing in this index.

 ["a", "b", "c", , "e", "f"].forEach(function (el, i) { console.log(el + " at " + i); }); // => "a at 0" "b at 1" "c at 2" "e at 4" "f at 5" 
+7
source

Since the array can have holes, and so you can iterate over the length, and not all values ​​will exist.

 x = new Array() [] x[0] = "zero" "zero" x[5] = "five" "five" x ["zero", undefined × 4, "five"] 3 in x false x.length 6 for (var i = 0; i < x.length; i++) { console.log(i, i in x, x[i])} 0 true "zero" 1 false undefined 2 false undefined 3 false undefined 4 false undefined 5 true "five" 
+3
source

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


All Articles