【问题标题】:return value inside foreachforeach 中的返回值
【发布时间】:2016-09-26 09:46:36
【问题描述】:

所以这很奇怪,我有一个这样的 foreach 函数:

  let cookieValue = '';

  cookieList.forEach(function(cookieItem) {
    const cookieParts = cookieItem.split('=');
    const value = cookieParts[1];
    const key = cookieParts[0];
    if (key.trim() === cookieName) {
      cookieValue = value;
      return cookieValue;
    }
  });

  return cookieValue;

效果很好,但是当我将 if 语句中的行更改为单行时:

return value;

它总是返回 undefined。

对这里可能发生的事情有什么想法吗?

【问题讨论】:

  • 系统完全忽略.forEach()回调返回的值。
  • 你期望它的表现如何?
  • 你到底想做什么?
  • 以这个简化但等效的示例为例:function foo() { function bar() { return 42; }; return 21; }foo() 返回什么?

标签: javascript foreach return


【解决方案1】:

forEach 的返回被忽略,但你可以使用 map 和 filter:

function getCookieValue(cookieList, cookieName) {
    var val = cookieList.map(function(cookieItem) {
        var cookieParts = cookieItem.split('=');
        var value = cookieParts[1];
        var key = cookieParts[0];
        return (key.trim() === cookieName) ? value : null;
    })
    .filter((value) => { return value != null })[0];
    return val;
}

let cookieValue = getCookieValue(["key1=val1", "key2=val2"], "key2"); // > "val2"

【讨论】:

  • Array.find 会更好
【解决方案2】:

您的代码起初运行“正常”,因为您手动更改了 cookieValue 的值。

Array.prototype.forEach 不会对您传递给它的回调的返回值做任何事情。

对于这种情况,我会使用Array.prototype.mapArray.prototype.reduce 的组合:

let cookieValue = cookieList.map(function(cookieItem) {
  const cookieParts = cookieItem.split('=');
  const value = cookieParts[1];
  const key = cookieParts[0];
  if (key.trim() !== cookieName) {
    return null;
  }
  return value;
}).reduce(function(a, b) {
  return a || b;
}, '');

return cookieValue;

【讨论】:

  • Array.find 会更好
  • 这只是一个偏好问题。
  • 它们都可以工作,但理解 map 和 reduce 方式要困难得多。
【解决方案3】:

您在 forEach 函数中的返回值在该函数中返回。通过将 return 放在外部函数中,您可以在调用该函数时返回该值。请参阅此简化示例。

function x(){
    function y(){
        return 5 // Does not return in the x function
    }
    y() // = 5
    return 7
}
x() // =7

您似乎正在寻找 Array.find。

let cookieValue = '';
return cookieList.find(function(cookieItem) {
  const cookieParts = cookieItem.split('=');
  const value = cookieParts[1];
  const key = cookieParts[0];
  return key.trim() === cookieName
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-30
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多