这是一个非常基本的问题,只是为了满足我的好奇心,但有没有办法做到这一点:
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语句,这有点烦人。
发布于 2012-01-16 12:51:57
用圆括号括起来,并在外面否定。
if(!(obj instanceof Array)) {
//...
}在这种情况下,优先级顺序很重要(https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence)。那!运算符位于instanceof运算符之前。
发布于 2013-03-12 19:05:16
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
}这是一个语法错误。像!=这样的运算符是单个运算符,而不是不应用于等于的运算符。没有像!instanceof这样的运算符,就像没有!<运算符一样。
发布于 2016-06-15 18:03:51
正如在其他答案中解释的那样,否定是不起作用的,因为:
“优先级很重要”
但是很容易忘记双括号,所以你可以养成这样做的习惯:
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
}尝试一下
https://stackoverflow.com/questions/8875878
复制相似问题