我是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