哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、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) {
当前回答
您也可以使用!!在变量之前检查它是否已定义。例如。
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 (elem) { // or !elem
会为你做这件事的!。。。这将检查以下情况:
undefined:如果值未定义且未定义null:如果它为null,例如,如果DOM元素不存在。。。空字符串:“”0:数字零NaN:不是数字假的
所以它将涵盖所有的情况,但我们也希望涵盖一些奇怪的情况,例如,一个带空格的字符串,比如这个“”,这将在javascript中定义,因为它在字符串中有空格。。。例如,在本例中,您使用trim()再添加一个检查,例如:
if(elem) {
if(typeof elem === 'string' && elem.trim()) {
///
此外,这些检查仅针对值,因为对象和数组在Javascript中的工作方式不同,所以空数组[]和空对象{}始终为true。
我创建了下面的图像,以显示答案的简要说明:
很难区分undefined和null。Null是一个值,当您想要指示变量没有特定值时,可以将其赋值给该变量。未定义是一个特殊值,它将是未分配变量的默认值。
var _undefined;
var _null = null;
alert(_undefined);
alert(_null);
alert(_undefined == _null);
alert(_undefined === _null);
测试未声明(未定义)变量的捷径是
if (typeof variable === "undefined") {
...
}
我发现它对于检测在浏览器外部运行的脚本(没有声明窗口变量)非常有用。
我根据对象使用两种不同的方式。
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。
typeof运算符将检查变量是否真的未定义。
if (typeof variable === 'undefined') {
// variable is undefined
}
与其他运算符不同,typeof运算符在与未声明的变量一起使用时不会引发ReferenceError异常。
但是,请注意,typeof null将返回“object”。我们必须小心避免将变量初始化为null的错误。为了安全起见,我们可以使用以下方法:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
有关使用严格比较==而不是简单相等==的更多信息,请参阅:JavaScript比较中应该使用哪个相等运算符(==vs==)?