!! ~ (틸드 / 뱅뱅 틸드가 아님)는 '포함 / 포함'배열 메서드 호출의 결과를 어떻게 변경합니까?
여기 jQuery inArray
페이지 의 주석을 읽으면 흥미로운 선언이 있습니다.
!!~jQuery.inArray(elm, arr)
이제 이중 느낌표가 결과를 boolean
값이있는 type으로 변환 할 것이라고 믿습니다 true
. 내가 이해하지 못하는 것은이 모든 것에서 물결표 ( ~
) 연산자를 사용하는 것입니다.
var arr = ["one", "two", "three"];
if (jQuery.inArray("one", arr) > -1) { alert("Found"); }
if
진술 리팩토링 :
if (!!~jQuery.inArray("one", arr)) { alert("Found"); }
고장:
jQuery.inArray("one", arr) // 0
~jQuery.inArray("one", arr) // -1 (why?)
!~jQuery.inArray("one", arr) // false
!!~jQuery.inArray("one", arr) // true
또한 물결표를 앞에 넣으면 결과가 -2
.
~!!~jQuery.inArray("one", arr) // -2
여기서 물결표의 목적을 이해하지 못합니다. 누군가가 그것을 설명하거나 리소스를 가리킬 수 있습니까?
물결표 연산자는 실제로 jQuery의 일부가 아닙니다. JavaScript 자체에서 비트 NOT 연산자입니다.
The Great Mystery of the Tilde (~)를 참조하십시오 .
정수에 대해 비트 논리 연산을 수행하고 있기 때문에 실험에서 이상한 숫자를 얻고 있습니다 (내가 아는 한, 2의 보수 또는 이와 비슷한 것으로 저장 될 수 있습니다 ...)
2의 보수 는 숫자를 이진수로 표현하는 방법을 설명합니다. 내가 옳았다 고 생각합니다.
.NET Framework ~
앞에 적용될 수있는 특별한 이유가 있습니다 $.inArray
.
원래,
~$.inArray("foo", bar)
할 수있는 더 짧은 방법입니다
$.inArray("foo", bar) !== -1
$.inArray
첫 번째 인수가 발견되면 배열에있는 항목의 인덱스를 반환하고 발견되지 않으면 -1을 반환합니다. 즉, "이 값이 배열에 있습니까?"라는 부울을 찾는 경우 -1이 진실 값이고 $ .inArray가 0 (잘못된 값)을 반환 할 때 부울 비교를 수행 할 수 없습니다. ), 그것은 실제로 배열의 첫 번째 요소에서 발견되었음을 의미합니다.
~
비트 연산자를 적용 하면가 -1
되고 0
0이`-1이됩니다. 따라서 배열에서 값을 찾지 못하고 비트 NOT을 적용하면 잘못된 값 (0)이 발생하고 다른 모든 값은 0이 아닌 숫자를 반환하고 진실한 결과를 나타냅니다.
if (~$.inArray("foo", ["foo",2,3])) {
// Will run
}
그리고 의도 한대로 작동합니다.
!!~expr
그렇지 않은 false
경우 expr
로 평가됩니다 . 와 동일하지만 깨짐 *-1
true
expr != -1
JavaScript 비트 연산 은 피연산자를 2의 보수 형식으로 부호있는 32 비트 정수로 변환 하기 때문에 작동 합니다. 따라서 !!~-1
다음과 같이 평가됩니다.
-1 = 1111 1111 1111 1111 1111 1111 1111 1111b // two's complement representation of -1
~-1 = 0000 0000 0000 0000 0000 0000 0000 0000b // ~ is bitwise not (invert all bits)
!0 = true // ! is logical not (true for falsy)
!true = false // duh
이외의 값 -1
은 하나 이상의 비트를 0으로 설정합니다. 반전하면 진실한 가치가 생성됩니다. !
진실 값에 연산자를 두 번 적용하면 부울 true가 반환됩니다.
와 함께 사용할 때 .indexOf()
결과가 다음 -1
과 같은지 확인하고 싶습니다 .
!!~"abc".indexOf("d") // indexOf() returns -1, the expression evaluates to false
!!~"abc".indexOf("a") // indexOf() returns 0, the expression evaluates to true
!!~"abc".indexOf("b") // indexOf() returns 1, the expression evaluates to true
* !!~8589934591
거짓으로 평가되므로질색을 (를) 테스트하는 데 안정적으로 사용할 수 없습니다 -1
.
~foo.indexOf(bar)
함수가 존재하지 않기 foo.contains(bar)
때문에 표현하는 일반적인 속기 contains
입니다.
일반적으로 "거짓"값이라는 JavaScript의 개념으로 인해 부울로 캐스트 할 필요가 없습니다. 이 경우 함수의 출력을 true
또는 로 강제하는 데 사용됩니다 false
.
jQuery.inArray()
-1
보수 ( ~
)가 인 "찾을 수 없음"을 반환 합니다 0
. 따라서 "찾을 수 없음"에 대해서는 ~jQuery.inArray()
거짓 값 ( 0
)을 반환하고 "발견됨"에 대해서는 진실 값 (음의 정수)을 반환합니다. !!
그런 다음 거짓 / 진정한 것을 실제 부울 false
/ 로 공식화합니다 true
. 따라서 "발견됨"및 "찾을 수 없음"에 대해 !!~jQuery.inArray()
줄 것 입니다.true
false
~
4 바이트는 int
이 수식 같다-(N+1)
그래서
~0 = -(0+1) // -1
~35 = -(35+1) // -36
~-35 = -(-35+1) //34
The ~
operator is the bitwise complement operator. The integer result from inArray()
is either -1, when the element is not found, or some non-negative integer. The bitwise complement of -1 (represented in binary as all 1 bits) is zero. The bitwise-complement of any non-negative integer is always non-zero.
Thus, !!~i
will be true
when integer "i" is a non-negative integer, and false
when "i" is exactly -1.
Note that ~
always coerces its operand to integer; that is, it forces non-integer floating point values to integer, as well as non-numeric values.
Tilde is bitwise NOT - it inverts each bit of the value. As a general rule of thumb, if you use ~
on a number, its sign will be inverted, then 1 will be subtracted.
Thus, when you do ~0
, you get -1 (0 inverted is -0, subtract 1 is -1).
It's essentially an elaborate, super-micro-optimised way of getting a value that's always Boolean.
You're right: This code will return false
when the indexOf
call returns -1; otherwise true
.
As you say, it would be much more sensible to use something like
return this.modifiedPaths.indexOf(path) !== -1;
The ~
operator is the bitwise NOT operator. What this means is that it takes a number in binary form and turns all zeroes into ones and ones into zeroes.
For instance, the number 0 in binary is 0000000
, while -1 is 11111111
. Likewise, 1 is 00000001
in binary, while -2 is 11111110
.
My guess is that it is there because it's a few characters shorter (which library authors are always after). It also uses operations that only take a few machine cycles when compiled into the native code (as opposed to the comparison to a number.)
I agree with another answer that it's an overkill but perhaps might make sense in a tight loop (requires performance gain estimation, though, otherwise may turn out to be premature optimization.)
I assume, since it is a bitwise operation, it is the fastest (computationally cheap) way to check whether path appears in modifiedPaths.
As (~(-1)) === 0
, so:
!!(~(-1)) === Boolean(~(-1)) === Boolean(0) === false
'developer tip' 카테고리의 다른 글
디렉터리에 폴더가 있는지 확인하고 C #을 사용하여 만듭니다. (0) | 2020.08.29 |
---|---|
UITabBarItem 이미지를 아래로 이동 하시겠습니까? (0) | 2020.08.29 |
탭바 항목 제목과 무관하게 uiviewcontroller 제목을 변경하는 방법 (0) | 2020.08.29 |
1999 년 10 월 12 일의 의미는 무엇입니까? (0) | 2020.08.29 |
투명 네비게이션 바 ios (0) | 2020.08.29 |