检查返回的函数值是否为null?

Mic*_*umo 1 javascript jquery

这个问题(或类似问题)似乎经常被问到,但是我尝试了许多方法来检查从我拥有的函数返回的值是否为null;无济于事。

我的函数,按名称获取URL参数:

function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}
Run Code Online (Sandbox Code Playgroud)

但是,显然可能没有参数,因此我需要检查返回的值。

进行console.log( getURLParameter('client') );退货null...但是进行空检查不起作用。

我尝试了以下方法:

if ( getURLParameter("client") !== null ) {

    alert("It's there matey!");

}

if ( getURLParameter("client") != null ) {

    alert("It's there matey!");

}

if ( ! getURLParameter("client") ) {

    alert("It's there matey!");

}
Run Code Online (Sandbox Code Playgroud)

这些似乎都不适合我。

我哪里出问题了?我可以在香草JS中或使用jQuery库进行此操作。

T.J*_*der 5

问题是decodeURI,当您传递字符串 "null"时,它返回字符串null。解决的方法是null在致电之前进行检查decodeURI。您可以通过将功能分解为几个部分来找到它:

function getURLParameter(name) {
    var rex = RegExp(name + '=' + '(.+?)(&|$)');
    var result = rex.exec(location.search);
    var rv = decodeURI(
      (result||[,null])[1]
    );
    return rv;
}
Run Code Online (Sandbox Code Playgroud)

...并在浏览器内置的调试器中进行浏览。

或对于那些喜欢console.log-style调试的人:

function getURLParameter(name) {
    var rex = RegExp(name + '=' + '(.+?)(&|$)');
    var result = rex.exec(location.search);
    console.log("typeof result = " + typeof result);
    console.log("result = " + result);
    var rv = decodeURI(
      (result||[,null])[1]
    );
    console.log("typeof rv = " + typeof rv);
    return rv;
}
Run Code Online (Sandbox Code Playgroud)

... getURLParameter("foo")向我们展示:

结果类型=对象
结果=空
typeof rv =字符串