哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
当前回答
这取决于您是否只关心变量是否已定义,或者是否希望它具有有意义的值。
检查类型是否未定义将检查变量是否已定义。
==空或!==null将仅检查变量的值是否完全为null。
==空或!=null将检查该值是否未定义或为null。
if(value)将检查变量是否为undefined、null、0或空字符串。
其他回答
if (typeof console != "undefined") {
...
}
或者更好
if ((typeof console == "object") && (typeof console.profile == "function")) {
console.profile(f.constructor);
}
适用于所有浏览器
很难区分undefined和null。Null是一个值,当您想要指示变量没有特定值时,可以将其赋值给该变量。未定义是一个特殊值,它将是未分配变量的默认值。
var _undefined;
var _null = null;
alert(_undefined);
alert(_null);
alert(_undefined == _null);
alert(_undefined === _null);
您也可以使用!!在变量之前检查它是否已定义。例如。
let dog = "woof";
let chineseCat; // Undefined.
console.log("1.");
console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");
chineseCat= "mao"; // dog and chineseCat are now defined.
console.log("2.");
console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");
输出:
1.
Both are NOT defined
2.
Both are defined
在大多数情况下,您会使用:
elem != null
与简单的if(elem)不同,它允许0、false、NaN和“”,但拒绝null或undefined,这使它成为一个很好的通用测试,用于检查参数或对象属性的存在。
其他检查也没有错,它们只是有不同的用途:
if(elem):如果elem被保证是一个对象,或者如果false、0等被认为是“默认”值(因此相当于undefined或null),则可以使用。typeof elem==“undefined”可用于指定的null对未初始化的变量或属性具有不同含义的情况。如果没有声明elem(即没有var语句,不是window的属性,或者不是函数参数),这是唯一不会抛出错误的检查。在我看来,这是相当危险的,因为它会让错别字不知不觉地溜走。要避免这种情况,请参阅以下方法。
与未定义的严格比较也很有用:
if (elem === undefined) ...
但是,由于全局undefined可以用另一个值重写,因此最好在使用变量之前在当前范围中声明变量undefined:
var undefined; // really undefined
if (elem === undefined) ...
Or:
(function (undefined) {
if (elem === undefined) ...
})();
此方法的第二个优点是JS minifiers可以将未定义的变量减少为单个字符,每次都可以节省几个字节。
为了有助于辩论,如果我知道变量应该是字符串或对象,我总是喜欢if(!variable),所以检查它是否是假的。这可以带来更干净的代码,例如:
if(数据类型!==“undefined”&&数据类型。url===“未定义”){var message='接收响应时出错';if(typeof data.error!==“undefined”){message=数据错误;}否则如果(数据类型.消息!==“未定义”){message=数据消息;}警报(消息);}
..可以简化为:
if(data&&!data.url){var message=data.error | | data.message | |'接收响应时出错';警报(消息)}