将null分配给javascript var-最终为String [英] Assign null to javascript var - ends up as String

查看:33
本文介绍了将null分配给javascript var-最终为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将变量初始化为以下内容:

I have initialized my variable as the following:

var name = null;

如果我检查像这样的值,它不会执行任何操作:

If I check it's value like this it doesnt do anything:

if(name == null) {
    alert("Name = null");
}

但是,如果我将if子句更改为该子句,它将起作用:

But if I change the if-clause to that, it works:

if(name == "null") {
    alert("Name = null");
}

为每一个帮助感到高兴.

Happy for every help.

推荐答案

您可能正在全局范围内运行它,在这种情况下, name 指的是

It's likely that you're running this is in global scope, in which case name refers to the Window.name property. Assigning a value to this property automatically causes the value to be converted to a string, for example, try opening up your browser's console and typing this:

var name = 123;
alert(typeof name); 

您很可能会收到一条警报,提示您读取 string .

You'll most likely get an alert that reads string.

但是,如果将其放置在 IIFE 中(并确保您拥有 var 声明),其行为符合预期:

However, if you place this in an IIFE (and ensure that you have a var declaration), it behaves as expected:

(function() {
    var name = null;
    if(name == null) {
        alert("Name = null"); // shows alert
    }
})();

这篇关于将null分配给javascript var-最终为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆