哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、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 (typeof variable === "undefined") {
...
}
我发现它对于检测在浏览器外部运行的脚本(没有声明窗口变量)非常有用。
其他回答
if (typeof console != "undefined") {
...
}
或者更好
if ((typeof console == "object") && (typeof console.profile == "function")) {
console.profile(f.constructor);
}
适用于所有浏览器
我更喜欢这种方法,因为它的准确性和简洁性:
变量x如果(x===无效0){console.log(“x未定义”)}其他{console.log(“x已定义”)}
正如在其他评论和回答中提到的,undefined不能保证是undefineed。因为它不是关键字,所以可以在全局范围以外的范围中将其重新定义为变量。这里有一个小例子可以说明这种细微差别:
var undefined='bar'console.log(`在全局范围内:${undefined}`)函数foo(){var undefined=“已定义”变量x如果(x===未定义){console.log(`x===undefined`)}其他{console.log(`x!==undefined`)}如果(x===无效0){console.log(`x===void 0`)}其他{console.log(`x!==void 0`)}}foo()
请参阅void以了解兼容性(IE5支持!?!!哇!)。
为了检查变量是否已被声明/设置,我使用了这个肮脏的技巧。
即使使用eval,我也没有找到将代码提取到函数的方法。点击下面的评论,了解原因。
"use strict";
// var someVar;
var declared;
try {
someVar;
declared = true;
} catch(e) {
declared = false;
}
if (declared) {
console.log("someVar is declared; now has the value: " + someVar);
} else {
console.log("someVar is not declared");
}
当您执行简单的作业和相关检查时,还有另一种简便的方法来检查这一点。只需使用条件(三元)运算符。
var values = typeof variable !== 'undefined' ? variable : '';
当您尝试使用引用变量的实例赋值来声明全局变量时,这也会很有用。
若你们想检查变量不应该是未定义的或空的。然后执行以下检查。
当声明变量时,如果您想检查值,这甚至很简单:它将同时执行未定义和空检查。
var values = variable ? variable : '';
我根据对象使用两种不同的方式。
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。