最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS array find() that returns something other than the found element - Stack Overflow

programmeradmin4浏览0评论

Here's some code that runs each value in the array against an expensiveOperation function, and returns the first one that meets some criteria.

let result = [1, 2, 3, 4, 5].find(value => {
  let newValue = expensiveOperation(value)
  return meetsCritera(newValue)
}
result = expensiveOperation(result)

But what's returned from the find function is the array value (e.g. 3), rather than the result of expensiveOperation(3). To get that final value, I need to run expensiveOperation once more outside the body of find.

How can I avoid running it once more and return the desired value from find. Is there another ES6 array function that would let me do this?

Here's some code that runs each value in the array against an expensiveOperation function, and returns the first one that meets some criteria.

let result = [1, 2, 3, 4, 5].find(value => {
  let newValue = expensiveOperation(value)
  return meetsCritera(newValue)
}
result = expensiveOperation(result)

But what's returned from the find function is the array value (e.g. 3), rather than the result of expensiveOperation(3). To get that final value, I need to run expensiveOperation once more outside the body of find.

How can I avoid running it once more and return the desired value from find. Is there another ES6 array function that would let me do this?

Share Improve this question asked Jan 20, 2017 at 19:23 user779159user779159 9,63216 gold badges65 silver badges94 bronze badges 2
  • your just returning the condition true or false not the value – Roljhon Commented Jan 20, 2017 at 19:29
  • 1 assign the value to a variable which has scope outside the function.... – Pranav C Balan Commented Jan 20, 2017 at 19:36
Add a ment  | 

3 Answers 3

Reset to default 4

You can always use a good old loop:

let result;
for (let value of [1, 2, 3, 4, 5]) {
  let newValue = expensiveOperation(value);
  if (meetsCritera(newValue)) {
    result = newValue;
    break;
  }
}

You could use Array#some and exit the loop if the criteria is met.

var expensiveOperation = a => 3 * a,
    meetsCritera = v => v > 10,
    result = (() => {
        var newValue;
        return [1, 2, 3, 4, 5].some(value => {
            newValue = expensiveOperation(value);
            return meetsCritera(newValue);
        }) && newValue;
    })();

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

This is a decent usecase for .reduce.

let result = [1, 2, 3, 4, 5].reduce((result, value) => {
  if (result) return result;

  let newValue = expensiveOperation(value)
  if (meetsCritera(newValue)) return newValue;
}, null);
发布评论

评论列表(0)

  1. 暂无评论