Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;

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

return value;

It returns undefined always.

Any ideas of what can be happening here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
187 views
Welcome To Ask or Share your Answers For Others

1 Answer

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...