2017-01-20 10 views
0

를 비동기 아니더라도 작동하지 않습니다 정의 된 객체. 콘솔에서 출력이 hello, im returning으로 표시되기 때문에이 기능이 실제로 돌아 오는 것을 확인할 수 있지만 console.log(filterDesiredURLs(tweet));undefined을 인쇄합니다. 익명 함수가 비동기 작업의 콜백으로 전달 될 것으로 예상되지만, 비동기 적이 지 않으므로 반환해야합니다. 무슨 일이야?는 나는 다음과 같은 기능이있다

+0

: 당신은 아마 filter 또는 findsome과 함께 원하는 당신이 원하는 수행합니다. 'Array # forEach'는 콜백의 반환 값을 무시합니다. – 4castle

+0

코드가 ['Array # filter'] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)와 ['Array # ('https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) '대신'forEach' 루프를 사용하십시오. – 4castle

답변

1

return은 함수 경계를 넘어서 작동하지 않습니다. 가장 안쪽의 함수에서만 반환됩니다. 당신은 내부 함수가 아닌 외부 함수에서 반환하고

function filterDesiredURLs(tweet) { 
    // First, you were missing a return in the outer function 
    // Without a return here, *this* function will return `undefined` 
    return tweet.entities.urls.filter(url => { 
    // We are using `filter` to reduce the URL list to only 
    // URLs that pass our test - this inner function needs to return 
    // a boolean (true to include the URL, false to exclude it) 
    return desiredURLs.some(regexPattern => { 
     // Finally, we use `some` to see if any of the regex patterns match 
     // This method returns a boolean value. If the function passed to it ever 
     // returns true, it terminates the loop and returns true 
     // Otherwise, it iterates over the entire array and returns false. 
     return regexPattern.test(url['expanded_url']); 
    }); 
    }); 
} 
+0

일반 표현식의 복잡성에 따라 * 정규 표현식의 복잡성에 따라 일반 표현식을 모두 "결합하여"결합한 다음 결합 된 정규 표현식을 사용하여 한 번 테스트하는 것이 더 적합 할 수 있습니다. 하지만 그것은 마이크로 최적화 일 가능성이 높습니다. –

1

return을 호출하면 가장 가까운 함수 (이 경우 익명 함수가 내제 forEach에 인수로 전달됨)에서 반환됩니다. docs 가입일

:

리턴 명령문 기능 실행을 종료하고 에 값 함수 호출자에게 반환 지정한다.

이 목표를 달성하기 위해, 당신은 이것을 시도 할 수 있습니다 :

function filterDesiredURLs(tweet) { 
    let found = false; 
    tweet.entities.urls.forEach((url) => { 
     desiredURLs.forEach((regexPattern) => { 
      if (regexPattern.test(url['expanded_url'])) { 
       console.log('hello, im returning'); 
       found = true; 
       /* don't need return because forEach does not expects a function that returns something; and you can't break forEach */ 
      } 
     }) 
    }) 
    return found; 
} 
+1

'return;'는 forEach를 깨뜨리지 않을 것이고, 그것은 단지 하나의 반복을 끝낼 것입니다. 'for' 루프에서'continue;'문과 같이 생각하십시오. – 4castle

+0

@ 4castle, 네 말이 맞아! tnks – mrlew

0

자바 스크립트 forEach 방법은 undefined를 반환합니다.

forEach은 배열을 변경 불가능하게 유지하고 새 배열을 반환하는 연산입니다. 코드에서 forEach 메서드가 호출되고 아무 것도 반환하지 않으므로 undefined입니다.