Javascript !instanceof If Statement

不羁的心 提交于 2019-12-03 02:29:31

问题


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.


回答1:


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.




回答2:


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.

In the case of the ! operator before the instanceof operator.

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.




回答3:


It is easy to forget the parenthesis (brackets) so you can make a habit of doing:

if(obj instanceof Array === false) {
    //The object is not an instance of Array
}

or

if(false === obj instanceof Array) {
    //The object is not an instance of Array
}

Try it here



来源:https://stackoverflow.com/questions/8875878/javascript-instanceof-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!