JavaScript 函數返回值

JavaScript定義帶返回值的函數有兩種方法:

1. 用var function_name = function(){}方式定義,示例如下:

// 這種方式需要將var getCurrentTime定義在調用之前
var getCurrentTime = function()
{
	var now = new Date();
	var timeStr = now.getHours() + '時' + now.getMinutes() + '分' + now.getSeconds() + '秒' + now.getMilliseconds();
	return timeStr;
}
// document.getElementById('now1').innerHTML = "當前時間是\t" + getCurrentTime();

這種方法要求將函數定義在調用之前,因爲他是把getCurrentTime當做變量(var)的。

2. (常用方法) 用functiongetValue(){}方式定義,直接返回結果,示例如下:

// document.getElementById('now2').innerHTML = "當前時間是\t" + getValue();
// 這種方式不要求將函數定義在調用之前
function getValue()
{
	var now = new Date();
	return now.toLocaleString();
}


這種方法在函數定義之前之後調用均可。

這兩種方式均可在函數的括號內加參數。完整代碼示例如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
        .text{margin-top:10px;	margin-left:0; background-color:#BBE;}
    </style>
    <title>函數返回值</title>
</head>

<body>
<div id='now1' class="text"></div>
<div id='now2' class="text"></div>

<script>
    // 這兩種方法都可以在括號內加參數

    // 這種方式需要將var getCurrentTime定義在調用之前
    var getCurrentTime = function()
    {
        var now = new Date();
        var timeStr = now.getHours() + '時' + now.getMinutes() + '分' + now.getSeconds() + '秒' + now.getMilliseconds();
        return timeStr;
    }
    document.getElementById('now1').innerHTML = "當前時間是\t" + getCurrentTime();

    document.getElementById('now2').innerHTML = "當前時間是\t" + getValue();
    // 這種方式不要求將函數定義在調用之前
    function getValue()
    {
        var now = new Date();
        return now.toLocaleString();
    }
</script>
</body>
</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章