return value inside foreach

后端 未结 3 1927
猫巷女王i
猫巷女王i 2020-12-12 05:49

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

  let cookieValue = \'\';

  cookieList.forEach(function(cookieItem) {
    const cookieParts = co         


        
3条回答
  •  旧巷少年郎
    2020-12-12 05:55

    Your code works "fine" at first because you're manually changing the value of cookieValue.

    Array.prototype.forEach doesn't do anything with the returning value of the callback you pass to it.

    For this case, I'd use a combination of Array.prototype.map and Array.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;
    

提交回复
热议问题