Javascript!If语句的instanceof

Javascript!If语句的instanceof,javascript,instanceof,Javascript,Instanceof,这是一个非常基本的问题,只是为了满足我的好奇心,但有没有办法做到这一点: if(obj !instanceof Array) { //The object is not an instance of Array } else { //The object is an instance of Array } if(obj instanceof Array) { //Do nothing here } else { //The object is not an in

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

if(obj !instanceof Array) {
    //The object is not an instance of Array
} else {
    //The object is an instance of Array
}
if(obj instanceof Array) {
    //Do nothing here
} else {
    //The object is not an instance of Array
    //Perform actions!
}
这里的钥匙不能用!在实例前面。通常我必须这样设置:

if(obj !instanceof Array) {
    //The object is not an instance of Array
} else {
    //The object is an instance of Array
}
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
}
正如其他人已经回答的那样,这是检查这一点的正确方法。所建议的其他两种策略将不起作用,应予以理解

如果是
不带括号的运算符

if (!obj instanceof Array) {
    // do something
}
在这种情况下,优先顺序很重要()。
运算符位于
运算符的
实例之前。所以,
!obj
首先计算为
false
(它相当于
!Boolean(obj)
);然后您将测试数组的
实例是否为false,这显然是否定的

如果是
操作符的
实例之前的code>操作符

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

这是一个语法错误。运算符,如
=是单个运算符,而不是不应用于等于的运算符。没有像
这样的运算符!instanceof
的方式与没有
的方式相同 如其他答案所述,否定不起作用,因为:

“优先顺序很重要”

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

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


试试看

@hrishikeshp19-我很确定您需要这些参数,我刚刚在chrome、IE和node中试过,每个主机都需要它们。@riship89参数是必需的,证明:
!!数组的obj instanceof
返回false(不正确),而
!!(obj instanceof Array)
返回true(正确)原因是!obj首先在if(!obj instanceof Array)中求值,该值为true(或false),然后变为if(bool instanceof Array),这显然是false。因此,按照建议用括号括起来。这个理由应该是答案的一部分,否则这个答案不会比下面的克里斯的答案更好@SergioTulentsev,你能不能帮我添加这样的内容:
在这种情况下,优先顺序很重要(https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence). 这个运算符位于instanceof运算符之前你的答案?注意。我本想对塞尔吉奥的回答发表评论,因为这显然是正确的,但我不是该组织的成员,所以没有足够的声望点来评论。只有解释问题原因的答案(比如这一个)才应该被接受…@chrismichaelscott在我看来,我确信我并不孤单,像你这样的答案是这里任何提问的人最想要的。它是明确的,切中要害的,并且分享了足够的信息和例子来解决所提出的问题。谢谢。我认为你应该得到这个名声,应该是被接受的答案。对我来说,这看起来比否定更干净。