zoukankan      html  css  js  c++  java
  • 一道js面试题看变量的作用域

    【问题】分别求下面程序的输出结果:   

    1.
        <script type="text/javascript">
            var a = 10;
            sayHi();
            function sayHi() {
                a = a + 10;
                document.write(a);
            }
            document.write(a);
        </script>
    --输出:20 20
    2.
        <script type="text/javascript">
            var a = 10;
            sayHi();
            function sayHi() {
                var a = a + 10;
                document.write(a);
            }
            document.write(a);
        </script>
    --输出:NaN 10
    3.
        <script type="text/javascript">
            var a = 10;
            sayHi();
            function sayHi() {
                a = a + 10;
                document.write(a);
                return a;
            }
            document.write(a);
            document.write(sayHi() + 10);
        </script>
    --输出:20 20 30 40
    4.
        <script type="text/javascript">
            var a = 10;
            sayHi();
            function sayHi() {
                var a = a + 10;
                document.write(a);
                return a;
            }
            document.write(a);
            document.write(sayHi() + 10);
        </script>
    --输出:NaN 10 NaN NaN 

    【分析】第1题和第3题比较容易理解。 第2题和第4题呢,就需要分析分析了。 

    以上测试主要考察的是变量作用域知识。 在函数里,局部变量优先级比全局变量优先级高,这本没什么,但若局部变量与全局变量重名,那就有的说了。sayHi里边,var a 就相当于 a 跟外边没联系了。重新定义a = a+10 ,那等号右边的a还没给个确切的值(此时输出的a是undefined)呢, 所以,执行var a=a+10后,a的值为NaN (注意:因为是参与了加法运算,所以是NaN,而不是undefined)。

    且看如下代码:

    <script type="text/javascript">
     var str='test';
     function shuchu(){
         document.write(str+'<br/>');
         var str='world';
         document.write(str+'<br/>');
     }
     shuchu();
     </script>
    --输出:
    undefined
    world

     原因:局部变量作用于整个作用域.
     原因解释:正因为局部变量作用于整个作用域,所以函数shuchu中的第一行document.write(str+'<br/>');中的str是用的局部变量,然而此时尚未赋值,所以会出现undefined.

    【如果C#】
    以上是在js脚本中的情况。 如下c#代码在编译时会报错:使用了未赋值的局部变量"a"

    public class TestScope
    {
            int a = 10;
            void SayHi()
            {
                int a = a + 10;
                Console.WriteLine(a);
            }
    }


    同样,如下c#代码在编译时会报错:局部变量"a"在声明之前无法使用。局部变量的声明隐藏字段"TestScope.a"

    public class TestScope
    {
           int a = 10;
           void SayHi()
           {
                a = 12;
                int a = 11;
           }
    }
  • 相关阅读:
    web_arcgis 步骤
    《程序员修炼之道》读后感
    《人月神话》读后感
    七天开发记录(6)
    七天开发记录(5)
    七天开发记录(4)
    七天开发记录(3)
    七天开发记录(2)
    七天开发记录(1)
    《梦断代码》读后感
  • 原文地址:https://www.cnblogs.com/buguge/p/3681764.html
Copyright © 2011-2022 走看看