是什么“〜”运算符在这个脚本中做? [英] what does "~" operator do in this script?

查看:65
本文介绍了是什么“〜”运算符在这个脚本中做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我即时删除特定索引中的数组,我附带了这个脚本:

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...

提前感谢

推荐答案


〜运算符在此脚本中的作用是什么?

what does "~" operator do in this script?

正如其他人所指出的,这是按位NOT运算符。这一切都很好,但在这个脚本中做的是问题。 : - )

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. :-)

这个想法可能做了几乎所说的话:如果 index 是一个数字,执行 splice 运算符对其操作数的第一件事是将其转换为数字(如果可以)。如果不能,结果是 NaN (不是数字),这是假的,因此条件将为false并且不会发生拼接

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.

但转换不会导致 NaN 几乎,因为我怀疑该代码的作者在想。 : - )

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

一些随机的例子说明了 splice

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

~-1 === 0

还有一些 splice

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

可能不太理想,它正试图用其中一些来做 splice 。例如, true 将使用索引 1 进行拼接, false 将是索引 0

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.

这篇关于是什么“〜”运算符在这个脚本中做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆