哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、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) {
当前回答
为了有助于辩论,如果我知道变量应该是字符串或对象,我总是喜欢if(!variable),所以检查它是否是假的。这可以带来更干净的代码,例如:
if(数据类型!==“undefined”&&数据类型。url===“未定义”){var message='接收响应时出错';if(typeof data.error!==“undefined”){message=数据错误;}否则如果(数据类型.消息!==“未定义”){message=数据消息;}警报(消息);}
..可以简化为:
if(data&&!data.url){var message=data.error | | data.message | |'接收响应时出错';警报(消息)}
其他回答
我的首选是typeof(elem)!='未定义'&&elem!=无效的
无论您选择什么,请考虑将检查放入这样的函数中
function existy (x) {
return typeof (x) != 'undefined' && x != null;
}
如果您不知道变量已声明,请继续使用typeof(x)!='未定义'&&x!=无效的
如果您知道变量已声明但可能不存在,可以使用
existy(elem) && doSomething(elem);
您正在检查的变量有时可能是嵌套属性。您可以使用prop | |{}来检查问题属性的存在性:
var exists = ((((existy(myObj).prop1||{}).prop2||{}).prop3||{})[1]||{}).prop4;
在每个属性之后,使用(…“| |{}”).nexPro,以便丢失的属性不会引发错误。
或者,您可以使用existy,如existy(o)&&exist(o.p)&&existiny(o.p.q)&&doSomething(o.p.q)
我根据对象使用两种不同的方式。
if( !variable ){
// variable is either
// 1. '';
// 2. 0;
// 3. undefined;
// 4. null;
// 5. false;
}
有时我不想将空字符串求值为false,所以我使用这种情况
function invalid( item ){
return (item === undefined || item === null);
}
if( invalid( variable )){
// only here if null or undefined;
}
如果你需要相反的东西,那么首先!变量变为!!变量,并且在无效函数中==变为!=函数名变为notInvalid。
您需要运算符的类型。明确地:
if (typeof variable !== 'undefined') {
// the variable is defined
}
您也可以使用!!在变量之前检查它是否已定义。例如。
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
if (typeof console != "undefined") {
...
}
或者更好
if ((typeof console == "object") && (typeof console.profile == "function")) {
console.profile(f.constructor);
}
适用于所有浏览器