为什么提示返回有时为null为字符串 [英] Why prompt returns sometimes null as string

查看:117
本文介绍了为什么提示返回有时为null为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一位朋友问我为什么这段代码无法正常取消提示。

a friend of mine asked me why this code doesn't work properly by canceling prompt.

<script type="text/javascript">
    var name = prompt("Enter your name:", "");
    if (!name) {
        name = "unknown";       
    }
    var ans =("<h2>" + "Hello, "+ name + "!"+"</h2>");      
    document.write(ans);        
</script>

这是jsfidle https://jsfiddle.net/085svr3u/

Here is jsfidle https://jsfiddle.net/085svr3u/

我发现,在上面的示例中,propmt返回null即。取消为null作为字符串。我不明白为什么。

I found out, that in the example above propmt returns "null" ie. null as string by cancel. And I have no idea why.

我尝试使用原始代码并重构一下。现在它按预期工作。但我仍然没有解释。

I tried to play with original code and refactored it a bit. Now it works as expected. But I still have no explanation.

<script type="text/javascript">

    function test() {
        var name = prompt("Enter your name:", "");
        if (!name) {
            name = "unknown";       
        }
        var ans =("<h2>" + "Hello, "+ name + "!"+"</h2>");      
        document.write(ans);        
    }

    test();
</script>

这里是修改后的版本 https://jsfiddle.net/085svr3u/1/

提前谢谢。

推荐答案

以下是您的回答

关键字名称在javascript中在全局范围内使用时会出现问题

The keyword 'name' causes problems when used in global scope in javascript

如果在第一种情况下,将'name'替换为'fname'或其他变量名称,它将停止给出null 。

If even in your first case, you replace 'name' with 'fname' or some other variable name it will stop giving null.

<script type="text/javascript">
    var fname = prompt("Enter your name:", "");
    if (!fname) {
        fname = "unknown";      
    }
    var ans =("<h2>" + "Hello, "+ fname + "!"+"</h2>");     
    document.write(ans);        
</script>

在第二种情况下,变量' name '在函数内部本地创建并且它与 window.name 不冲突。因此它可以正常工作

In the second case variable 'name' is locally created inside the function and it does not conflict with window.name. Hence it works properly

这篇关于为什么提示返回有时为null为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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