return value inside foreach

后端 未结 3 1926
猫巷女王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 06:10

    Your return value in the forEach function return in that function. By placing the return in the outer function, you return that value when that function is called. See this simplified example.

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

    You seem like you are looking for 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
    });
    

提交回复
热议问题