Javascript !instanceof If Statement

前端 未结 3 1257
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-12 21:11

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 obje         


        
3条回答
  •  时光说笑
    2020-12-12 21:56

    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.

提交回复
热议问题