无法使Javascript数组“包含”在String原型中工作

时间:2018-12-06 21:37:10

标签: javascript

当我在String原型中使用Javascript数组“ includes”函数时,如果希望返回“ true”,则返回“ false”-为什么有任何想法?

String.prototype.isIn = function (...constants) {
    var _this = this; //safety measure
    console.log("_this = " + _this);
    console.log("constants = " + constants);
    console.log("constants[1] = " + constants[1]);
    console.log("return value = " + constants.includes(_this));
    return constants.includes(_this);
}

console.log("'isIn' result = " + 'dog'.isIn('cat', 'dog', 'bat')); // why is this not "true"?

console.log("'includes' result = " + ['cat', 'dog', 'bat'].includes('dog')); // true, as expected

我已经尝试过Chrome版本70.0.3538.110(正式版本)(64位)脚本编辑器和nodejs v8.12.0

1 个答案:

答案 0 :(得分:2)

我建议使用this中的valueOf,因为this包含原型属性,但是您需要使用原始值来进行includes的检查(严格检查)。

String.prototype.isIn = function (...constants) {
    return constants.includes(this.valueOf());
};

var pets = ['cat', 'dog', 'bat'];

console.log("'isIn' result = " + 'dog'.isIn('cat', 'dog', 'bat')); // why is this not "true"?