Javascript !instanceof If Statement

Javascript !instanceof If Statement

本文关键字:Statement If instanceof Javascript      更新时间:2023-09-26

这是一个非常基本的问题,只是为了满足我的好奇心,但有没有办法做到这一点:

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语句有点烦人。

用括号括起来,在外面取反。

if(!(obj instanceof Array)) {
    //...
}

在这种情况下,优先顺序很重要。请参阅:操作员优先级。

!运算符位于instanceof运算符之前。

if (!(obj instanceof Array)) {
    // do something
}

这是正确的检查方式吗?正如其他人已经回答的那样。已经提出的另外两种策略是行不通的,应该理解。。。

在没有括号的!运算符的情况下。

if (!obj instanceof Array) {
    // do something
}

在这种情况下,优先顺序很重要(https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence)。!运算符位于instanceof运算符之前。因此,!obj首先评估为false(相当于! Boolean(obj));那么你正在测试false instanceof Array,它显然是阴性的。

!运算符的情况下,在instanceof运算符之前。

if (obj !instanceof Array) {
    // do something
}

这是一个语法错误。与应用于EQUALS的NOT相反,!=等运算符是单个运算符。与没有!<运算符一样,没有!instanceof这样的运算符。

如其他答案所述,否定不起作用,因为:

"优先顺序是重要的";

但是很容易忘记双括号,所以你可以养成这样做的习惯:

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

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

请尝试此处