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.