JavaScript(五)之 函数的定义

一、第一种声明函数的方式

function 函数名(){

}

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
    <title>流程控制语句</title>
</head>
<body>
<script type="text/javascript">
    function generateTable(rows ,cols){
        document.write("<table border='1' align='center'>");
        for(var i=0; i<rows; i++){
            document.write("<tr>");
            for(var j=0; j<cols; j++){
                document.write("<td>" + i + "行" + j + "列" + "</td>");
            }
            document.write("</tr>")
        }
        document.write("</table>");
    }
</script>
<input type="button" value="生成表格" onclick="generateTable(5,7)"/>
</body>
</html>

二、第二种方式

匿名函数 :var 变量名(函数名)= function(参数列表)

onclick=变量名(参数列表)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
    <title>流程控制语句</title>
</head>
<body>
<script type="text/javascript">
    var generateTable = function (rows ,cols){
        document.write("<table border='1' align='center'>");
        for(var i=0; i<rows; i++){
            document.write("<tr>");
            for(var j=0; j<cols; j++){
                document.write("<td>" + i + "行" + j + "列" + "</td>");
            }
            document.write("</tr>")
        }
        document.write("</table>");
    }
</script>
<input type="button" value="生成表格" onclick="generateTable(5,7)"/>
</body>
</html>

三、第三种方式:参数,前面都是参数,函数体是最后一个参数

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
    <title>function</title>
</head>
<body>
<script type="text/javascript">
    var add = new Function("x","y","var result = x + y; return x+y;");
    alert(add(4,5));
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/ada_yangyang/article/details/81203356