JS预编译面试题二则

<script> 
  var x = 1, y = z = 0; 
  function add(n) { 
  n = n+1; 
  } 
  y = add(x);
  function add(n) { 
  n = n + 3; 
  } 
  z = add(x);
  console.log(x);
  console.log(y);
  console.log(z);
</script>

输出结果为:

x=1  

y=undefined

z=undefined

函数表达式没有return 所以为undefined

 

<script>  
   var x = 1, y = z = 0;  
   function add(n) {  
      return n = n+1;  
  }  
   y = add(x);    
   function add(n) {  
      return n = n + 3;  
   }  
   z = add(x);  
   console.log(x,y,z)  
</script>

输出结果为:

当函数声明重名时后面的会覆盖前面的,所以n=n+1会被n=n+3覆盖,所以y和z的值都为4.

posted @ 2018-12-18 17:19  帅帅鼠标  阅读(694)  评论(0编辑  收藏  举报