자바 스크립트에서 이중 부정 (!!)-목적은 무엇입니까? [복제]
가능한 중복 :
무엇입니까! 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입니다 )
부울로 캐스팅됩니다. 첫 번째는 !
그것을 한 번 무시하고 다음과 같이 값을 변환합니다.
undefined
에true
null
에true
+0
에true
-0
에true
''
에true
NaN
에true
false
에true
- 다른 모든 표현
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
'programing tip' 카테고리의 다른 글
마스터 프로세스의 STDOUT 및 STDERR에 nginx access_log 및 error_log 로그가 있음 (0) | 2020.07.25 |
---|---|
최고의 프로그래밍 기반 게임 (0) | 2020.07.25 |
D3.js : 임의의 요소에 대해 계산 된 너비와 높이를 얻는 방법은 무엇입니까? (0) | 2020.07.25 |
CPAN에 모든 종속성을 설치하도록하려면 어떻게합니까? (0) | 2020.07.25 |
typescript에서 두 날짜 사이의 시간을 계산하는 방법 (0) | 2020.07.25 |