Javascript呼叫函數

呼叫函數

呼叫函數時,依序傳入參數即可:

abs(10); / / 返回10

abs(-9); // 返回9

由於JavaScript允許傳入任意個參數而不影響調用,因此傳入的參數比定義的參數多也沒問題,雖然函數內部並不需要這些參數:

abs(10, 'blablabla'); // 回傳10

abs(-9, 'haha', 'hehe', null); // 回傳9

傳入的參數比定義的少也沒問題:

abs(); // 傳回NaN

此時abs(x)函數的參數x將收到undefined,計算結果為NaN。

要避免收到undefined,可以對參數進行檢查:

function abs(x) {
    if (typeof x !== 'number') {
        throw 'Not a number';
    }
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}

下面的案例仔細觀察如何使用函數 的呼叫

<!DOCTYPE html>
<html>
<body>
<p>点击这个按钮,来调用带参数的函数。</p>
<button onclick="myFunction('学生','XXX')">点击这里</button>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + "," + job);
}
</script>
</body>
</html>


繼續學習
||
<!DOCTYPE html> <html> <body> <p>请点击其中的一个按钮,来调用带参数的函数。</p> <button onclick="myFunction('Harry Potter','Wizard')">点击这里</button> <button onclick="myFunction('Bob','Builder')">点击这里</button> <script> function myFunction(name,job) { alert("Welcome " + name + ", the " + job); } </script> </body> </html>
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!