-3

I was looking for an easy way to break out of forEach. This answer mentions using the some method, but that doesn't give you the index of the current element: How to short circuit Array.forEach like calling break?

I found that setting the array to false will break the forEach "loop". Is that valid or a hack?

Community
  • 1
  • 1
webXL
  • 1,630
  • 1
  • 15
  • 21

2 Answers2

2

If you mean by setting its .length to the current index in the iteration, then yes, it's "valid", but be aware that in doing so, you're clearing any Array members from that point forward.

var arr = ["foo","bar","baz"];

console.log(arr.length); // 3

arr.forEach(function(v, i) {
    if (i == 1)
        arr.length = i;
    else 
        console.log(v);
});

console.log(arr.length); // 1

If you set the .length to false, you're effectively setting it to 0, and so you're clearing the entire Array.

Using .some or .every seems more sensible to me.


I should note that the iteration doesn't necessarily stop, but your callback won't be invoked because the native .forEach() does not invoke the callback for non-existent properties. According to the spec, the length in cached.

This can be tested by expanding the Array during the iteration. The added members are never reached.

I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
0

According to the documentation, the index of the current element is passed as the 2nd parameter to the callback function:

Syntax: array.some(callback[, thisObject])

callback is invoked with three arguments: 
   1. the value of the element
   2. the index of the element
   3. the Array object being traversed

See documentation here


More importantly...

Is there any reason you can't do it the normal way:

var matchIndex = -1;
for (i = 0; i < someArray.length; i++) {
    if (isFound(someArray[i])) {
        matchIndex = i;
        break;
    }
}
alert("Mathing index: " + matchIndex);
jahroy
  • 22,322
  • 9
  • 59
  • 108