instanceof的右侧不可调用

时间:2017-04-19 17:23:32

标签: javascript

所以,我正在尝试使用javascript创建一个简单的Discord Bot,我想检测一个玩家用户名是否在禁止列表中。 我有一个数组

var banned = ['Andrew','David']

和if

if (message.author.username instanceof banned) {.....

但是当我运行它时,它会输出

if (message.author.username instanceof banned)
                            ^

TypeError: Right-hand side of 'instanceof' is not callable

我该怎么办?

5 个答案:

答案 0 :(得分:10)

这不是instanceof的用途。 instanceof用于查看对象是否是特定构造函数的实例(例如:banned instanceof Array)。

如果您只想查看元素是否在数组中,可以使用.indexOf()

if(banned.indexOf(message.author.username) != -1)

答案 1 :(得分:3)

instanceof用于检查对象是否是类的实例。你想要做的是检查一个字符串是否在这样的数组中:

if (banned.indexOf(message.author.username) >= 0) {...

答案 2 :(得分:2)

我在 vue / nuxt js 上遇到了同样的错误。

问题在于道具类型设置错误:

blog: {
  type: {},
  required: false,
},

正确的做法是设置类型 Object 而不是 {}

blog: {
  type: Object,
  required: false,
},

答案 3 :(得分:1)

instanceof用于查看对象是否属于特定类型。您正在尝试查看对象是否是数组的成员。

尝试使用Array对象的includesindexOf方法。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

答案 4 :(得分:0)

我知道我迟到了回答,但在代码可维护性和代码的第一印象时,我肯定会考虑includes()

ES2016规范 包含includes()数组数据结构。 includes()检查数组是否包含某个元素,并根据需要返回truefalse

但是在 ES5 中,我们习惯用indexOf()方法执行这样的操作。

为什么要使用includes

  1. includes方法找到NaNundefined,而indexOf方法则找不到。 在数组中查找NAN的示例:

    const  array = [NaN];
    if (array.indexOf(NaN) == -1){
        console.log("NaN not found in the array");//NaN not found in the array
    }
    
    const  array1 = [NaN];
    
    if (array1.includes(NaN)){
        console.log("true. NAN was found in the array");// true. NAN was found in the array
    }
    

    在数组中查找undefined的示例:

    const array = [, , , ,];
    
    if(array.includes(undefined)){
        console.log("true array elements are undefined");// true array elements are undefined
    } 
    
    const array1 = [, , , ,];
    
    if(!array1.indexOf(undefined) == -1 ){
        console.log("true. array elements are undefined");
    }else {
        console.log("Sorry can't find undefined");// Sorry can't find undefined
    }
    
  2. includes方法无法区分-0+0(这不是错误,但显然是javascript如何运作。

     const a = [-0].includes(+0);
     console.log(a);//true
    
  3. 在很多情况下,我看到indexOfinclude快一点。这取决于您需要妥协的地方。此外,与lodash的includes方法相比,ES6 includes的效果非常快。

    Performance comparison source.