Javascript检查参数是否包含此关键字

时间:2015-11-18 12:24:29

标签: javascript

我在检查包含关键字的javascript函数时遇到问题。

所以,这是我的代码:

function check(el) {        
    if (el === this) {

        return el;
    }
    else {
        alert("not contain this keyword");
    }
}
check(this);

它始终显示alert()

我尝试el == this, 我尝试el = this

两者仍无效。

是否可以使用 typeof 检查?

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

如果您尝试匹配“this”文本,请在此处附加单引号或双引号。如果传递的字符串包含“this”

,则以下代码会发出警报
function check(e1) {
    if (e1.indexOf("this") > -1) {
        alert("contain!");
        return e1;
    } else {
        alert("not contain this keyword");
    }
}
check("this");

以下代码检查传递的单词是否只是“this”

function check(el) {
    if (el === "this") {
        alert("contain!");
        return el;
    } else {
        alert("not contain this keyword");
    }
}
check("this");

答案 1 :(得分:0)

如果您正在尝试匹配字符串(将文本包装在单引号/双引号内)。使用以下代码。

function check(el) {

    if (el === 'this') {
        alert("contain!");
        return el;
    } else {
        alert("not contain this keyword");
    }
}

check('this');
相关问题