Closed Bug 614896 Opened 14 years ago Closed 14 years ago

Could Array.some return the matched element instead of true or false?

Categories

(Core :: JavaScript Engine, enhancement)

enhancement
Not set
normal

Tracking

()

RESOLVED INVALID

People

(Reporter: tabutils+bugzilla, Unassigned)

Details

User-Agent:       Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 (.NET CLR 3.5.30729)
Build Identifier: 

Sometimes it is needed to find the first element matching a condition in an array, but I don't want to iterate over the whole array. Array.some will be helpful if it returns the matched element or null instead of true or false.

Reproducible: Always
No, because the thing that "some" is matching could itself be false!

arr = [true, true, true, false];
arr.some(function (v) { return v == false; }) === true;

If you want to capture the value, I would recommend doing this:

var first;
if (arr.some(function (v) { first = v; return condition(v); })) {
  /* do something with first */
}
Status: UNCONFIRMED → RESOLVED
Closed: 14 years ago
Resolution: --- → INVALID
You need to log in before you can comment on or make changes to this bug.