Javascript !instanceof If 语句
这是一个非常基本的问题,只是为了满足我的好奇心,但是有没有办法做这样的事情:
if(obj !instanceof Array) {
//The object is not an instance of Array
} else {
//The object is an instance of Array
}
这里的关键是能够使用 NOT !在实例前面。通常我必须设置的方式是这样的:
if(obj instanceof Array) {
//Do nothing here
} else {
//The object is not an instance of Array
//Perform actions!
}
当我只想知道对象是否是特定类型时,必须创建 else 语句有点烦人。
This is a really basic question really just to satisfy my curiosity, but is there a way to do something like this:
if(obj !instanceof Array) {
//The object is not an instance of Array
} else {
//The object is an instance of Array
}
The key here being able to use the NOT ! in front of instance. Usually the way I have to set this up is like this:
if(obj instanceof Array) {
//Do nothing here
} else {
//The object is not an instance of Array
//Perform actions!
}
And its a little annoying to have to create an else statement when I simply want to know if the object is a specific type.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
括在括号内并在外面取反。
在这种情况下,优先顺序很重要。
请参阅:运算符优先级。
!
运算符位于instanceof
运算符之前。Enclose in parentheses and negate on the outside.
In this case, the order of precedence is important.
See: Operator Precedence.
The
!
operator precedes theinstanceof
operator.是检查此问题的正确方法 - 正如其他人已经回答的那样。建议的其他两种策略将不起作用,应该被理解......
在不带括号的
!
运算符的情况下。在这种情况下,优先顺序很重要(https://developer.mozilla.org /en-US/docs/JavaScript/Reference/Operators/Operator_Precedence)。
!
运算符位于instanceof
运算符之前。因此,!obj
首先评估为false
(它相当于!Boolean(obj)
);那么你正在测试是否false instanceof Array
,这显然是否定的。对于
!
运算符位于instanceof
运算符之前的情况。这是一个语法错误。
!=
等运算符是单个运算符,与应用于 EQUALS 的 NOT 不同。不存在!instanceof
这样的运算符,就像不存在!<
运算符一样。Is the correct way to check for this - as others have already answered. The other two tactics which have been suggested will not work and should be understood...
In the case of the
!
operator without brackets.In this case, the order of precedence is important (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence). The
!
operator precedes theinstanceof
operator. So,!obj
evaluated tofalse
first (it is equivalent to! Boolean(obj)
); then you are testing whetherfalse instanceof Array
, which is obviously negative.In the case of the
!
operator before theinstanceof
operator.This is a syntax error. Operators such as
!=
are a single operator, as opposed to a NOT applied to an EQUALS. There is no such operator as!instanceof
in the same way as there is no!<
operator.正如其他答案中所解释的,否定不起作用,因为:
但是很容易忘记双括号,因此您可以养成这样做的习惯:
或
尝试一下 这里
As explained in the other answers negation doesn't work because:
But it is easy to forget the double parenthesis so you can make a habit of doing:
or
Try it here