我是JavaScript新手,我只是想了解为什么'z'回到未定义状态。为什么这是'undefined'
var z = functionWithParameters(4, 3);
function functionWithParameters(x, y) {
if (typeof z !== 'undefined') {
document.getElementById("functionWithParameters").innerHTML = z;
console.log('inside function: ' + z);
console.log('inside function: z is a ' + typeof z);
}
console.log('before return: z = ' + z);
return x * y;
}
console.log('outside function: z = ' + z);
<p id = "functionWithParameters"></p>
<script>
functionWithParameters(4, 3);
</script>
如果我的代码运行,没有任何评论,它的结果:
before return: z = undefined
outside function: z = 12
inside function: 12
inside function: z is a number
before return: z = 12
如果我删除的:if(typeof运算ž== '未定义'! ),代码结果如下:
inside function: undefined
inside function: z is a undefined
before return: z = undefined
TypeError: document.getElementById(...) is null[Learn More] (from Firefox),
和行:console.log('outsi de函数:z ='+ z);不执行。我虽然可能这是因为该函数有一个返回语句,但注释返回没有改变结果。
任何帮助理解这将是非常棒的。 感谢您的任何反馈意见。
我的猜测是var提升。因此,'z'没有给出值并且是未定义的。 – Li357
逻辑没有意义。在函数中如何定义一个依赖函数返回的变量? – charlietfl
@charlietfl我不知道这个例子,但它在递归关系算法中很有意义。 – Linek