0

我有以下代码:

var store = window.localStorage;
var a = store.getItem('AccountID');
var b = store.getItem('CityID')

我怎样才能使它成为我的 refreshGrid("Page"); 函数仅在这两个都设置为值时运行?

4

4 回答 4

7

如果要检查它们是否明确null,只需将值与null

if(a !== null && b !== null) {
    //Neither is null
}

如果您在其中存储应该始终评估为 的值,则true可以跳过相等检查(如果该特定存储项中没有存储任何内容,这仍然会失败,因为null它是虚假的):

if(a && b) {
    //Neither is falsy
}
于 2012-05-02T08:17:50.783 回答
1

你可以使用这个:

var a; var b;

if (a == null && b == null) {
   //a and b are null
}

或者

if (!a && !b) {
   //a and b are null, undefined, 0 or false
}

对于 James:alert(null == undefined) // 返回 true

希望这可以帮助。

于 2012-05-02T08:20:26.667 回答
0

我认为以下代码是您正在寻找的。

if(!!a && !!b){

  alert("this is not null")

}else{

  alert("this is null")

}
于 2012-05-02T08:23:07.690 回答
0

在函数顶部使用保护条件:

function myFunction() {
    if(a==null || b==null) return;
    // ... rest of the code here
}
于 2012-05-02T08:19:21.503 回答