哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))

if (elem) { // or !elem

or

if (typeof elem !== 'undefined') {

or

if (elem != null) {

当前回答

我根据对象使用两种不同的方式。

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(!variable),所以检查它是否是假的。这可以带来更干净的代码,例如:

if(数据类型!==“undefined”&&数据类型。url===“未定义”){var message='接收响应时出错';if(typeof data.error!==“undefined”){message=数据错误;}否则如果(数据类型.消息!==“未定义”){message=数据消息;}警报(消息);}

..可以简化为:

if(data&&!data.url){var message=data.error | | data.message | |'接收响应时出错';警报(消息)}

为了使if条件正确工作,我们必须使用关键字let来创建变量。

let name = undefined; 
if (name) { 
    alert('valid')
};

很难区分undefined和null。Null是一个值,当您想要指示变量没有特定值时,可以将其赋值给该变量。未定义是一个特殊值,它将是未分配变量的默认值。


var _undefined;
var _null = null;

alert(_undefined); 
alert(_null); 
alert(_undefined == _null);
alert(_undefined === _null);

在许多情况下,使用:

if (elem) { // or !elem

会为你做这件事的!。。。这将检查以下情况:

undefined:如果值未定义且未定义null:如果它为null,例如,如果DOM元素不存在。。。空字符串:“”0:数字零NaN:不是数字假的

所以它将涵盖所有的情况,但我们也希望涵盖一些奇怪的情况,例如,一个带空格的字符串,比如这个“”,这将在javascript中定义,因为它在字符串中有空格。。。例如,在本例中,您使用trim()再添加一个检查,例如:

if(elem) {

if(typeof elem === 'string' && elem.trim()) {
///

此外,这些检查仅针对值,因为对象和数组在Javascript中的工作方式不同,所以空数组[]和空对象{}始终为true。

我创建了下面的图像,以显示答案的简要说明:

测试未声明(未定义)变量的捷径是

if (typeof variable === "undefined") {
  ...
}

我发现它对于检测在浏览器外部运行的脚本(没有声明窗口变量)非常有用。