programing tip

자바 스크립트에서 이중 부정 (!!)-목적은 무엇입니까?

itbloger 2020. 7. 25. 10:40
반응형

자바 스크립트에서 이중 부정 (!!)-목적은 무엇입니까? [복제]


가능한 중복 :
무엇입니까! JavaScript가 아닌 연산자입니까?

이 코드를 발견했습니다

function printStackTrace(options) {
    options = options || {guess: true};
    var ex = options.e || null, guess = !!options.guess;
    var p = new printStackTrace.implementation(), result = p.run(ex);
    return (guess) ? p.guessAnonymousFunctions(result) : result;
}

그리고 왜 이중 부정이 궁금 할 수 없었습니까? 같은 효과를 얻을 수있는 다른 방법이 있습니까?

(코드는 https://github.com/eriwen/javascript-stacktrace/blob/master/stacktrace.js입니다 )


부울로 캐스팅됩니다. 첫 번째는 !그것을 한 번 무시하고 다음과 같이 값을 변환합니다.

  • undefinedtrue
  • nulltrue
  • +0true
  • -0true
  • ''true
  • NaNtrue
  • falsetrue
  • 다른 모든 표현 false

그런 다음 다른 사람은 !다시 무시합니다. 정확히 해당하는 부울에 대한 간결 캐스트, ToBoolean는 이유만으로 !되어 그 부정으로 정의 . 그러나 조건 연산자의 조건으로 만 사용되므로 동일한 방식으로 진실성을 결정하기 때문에 여기서는 필요하지 않습니다.


var x = "somevalue"
var isNotEmpty = !!x.length;

조각으로 나누자.

x.length   // 9
!x.length  // false
!!x.length // true

따라서 "truethy"\ "falsy"값을 부울로 변환하는 데 사용됩니다.


다음 값은 조건문 에서 false와 같습니다 .

  • 그릇된
  • 없는
  • 찾으시는 주소가 없습니다
  • 빈 문자열 ""(\ '')
  • 숫자 0
  • 수 NaN

다른 모든 값은 true와 같습니다.


이중 부정은 "거친"또는 "거짓"값을 부울 값 true또는 으로 바꿉니다 false.

Most are familiar with using truthiness as a test:

if (options.guess) {
    // runs if options.guess is truthy, 
}

But that does not necessarily mean:

options.guess===true   // could be, could be not

If you need to force a "truthy" value to a true boolean value, !! is a convenient way to do that:

!!options.guess===true   // always true if options.guess is truthy

참고URL : https://stackoverflow.com/questions/10467475/double-negation-in-javascript-what-is-the-purpose

반응형