Javascript !instanceof If 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8875878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript !instanceof If Statement
提问by ryandlf
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:
这里的关键是能够使用 NOT ! 在实例前。通常我必须设置的方式是这样的:
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.
当我只想知道对象是否是特定类型时,不得不创建一个 else 语句有点烦人。
回答by Sergio Tulentsev
Enclose in parentheses and negate on the outside.
用括号括起来并在外面否定。
if(!(obj instanceof Array)) {
//...
}
In this case, the order of precedence is important (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence). The ! operator precedes the instanceof operator.
在这种情况下,优先顺序很重要(https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence)。这 !运算符在 instanceof 运算符之前。
回答by chrismichaelscott
if (!(obj instanceof Array)) {
// do something
}
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.
在!
操作符没有括号的情况下。
if (!obj instanceof Array) {
// do something
}
In this case, the order of precedence is important (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence). The !
operator precedes the instanceof
operator. So, !obj
evaluated to false
first (it is equivalent to ! Boolean(obj)
); then you are testing whether false instanceof Array
, which is obviously negative.
在这种情况下,优先顺序很重要(https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence)。该!
运营商先于instanceof
运营商。因此,!obj
评估为false
first(相当于! Boolean(obj)
);那么您正在测试是否false instanceof Array
,这显然是负面的。
In the case of the !
operator before the instanceof
operator.
在!
运算符之前的情况下instanceof
。
if (obj !instanceof Array) {
// do something
}
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.
这是一个语法错误。诸如此类的!=
运算符是单个运算符,而不是应用于 EQUALS 的 NOT。没有这样的运算符,就像!instanceof
没有!<
运算符一样。