JavaScript 函数返回值 | 您所在的位置:网站首页 › js函数没有返回值会输出之前存储的值吗对吗 › 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(); }这种方法在函数定义之前之后调用均可。 这两种方式均可在函数的括号内加参数。完整代码示例如下: .text{margin-top:10px; margin-left:0; background-color:#BBE;} 函数返回值 // 这两种方法都可以在括号内加参数 // 这种方式需要将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(); } |
今日新闻 |
推荐新闻 |
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 |