JavaScript 函数返回值

来源:互联网 发布:unity3d架构 编辑:程序博客网 时间:2024/05/21 11:15

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>


0 0
原创粉丝点击