3

Hi im deleting an array from specific index, and I came with this script:

var arr = [1,2,3,4];
var index = 2;
if (~index) arr.splice(index, 1);

I google "what does "~" operator do in this script?" and I can't find any answer I guess I'm doing an wrong search can anyone could explain me this operator and what's he name for a properly search?

I have an little suspect that is kind of comparing against (!)(undefined) but not sure...

thanks in advance

4

1 回答 1

4

what does “~” operator do in this script?

As others have pointed out, it's the bitwise NOT operator. Which is all well and good, but what's it doing in this script was the question. :-)

The idea was probably to do pretty much what you said: If index is a number, do the splice. The first thing the ~ operator does to its operand is convert it to a number if it can. If it can't, the result is NaN ("not a number"), which is falsey, and so the condition would be false and the splice wouldn't happen.

But the conversion doesn't result in NaN nearly as often as I suspect the author of that code thought. :-)

Some random examples of things that won't do the splice:

~-1 === 0

And some that will do the splice:

~"foo" === -1
~0 === -1
~1 === -2
~2 === -3
~true === -2
~false === -1
~-2 === 1
~undefined === -1
~null === -1
~NaN === -1

Probably not ideal that it's trying to do the splice with some of those. For instance, the true will make it do a splice using index 1, the false will be index 0.

于 2013-07-11T18:34:20.333 回答