foreach 中的返回值

2022-01-19 00:00:00 return foreach javascript

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

So this is very weird, I have a foreach function like this:

  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 语句中的行更改为单行时:

which works fine, however when I change the lines inside the if statement to a single line:

return value;

它总是返回 undefined.

It returns undefined always.

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

Any ideas of what can be happening here?

推荐答案

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

The return of forEach is ignored but you can use map and 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"

相关文章