js中的函式定義有兩種方式,
1.函式傳入的引數可以沒有型別標注,可以傳入任意型別的數值,
function 函式名(引數){
}
通過代碼實作一下,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
//函式定義
function test(a,b){
alert("傳入了"+a+b);
}
//函式運行
test("hello","js");
</script>
</body>
</html>
效果圖;

2.
函式名 = function(引數){
}
通過代碼實作一下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
//函式定義
test = function(a){
alert("你傳入了"+a);
}
//函式呼叫
test("hello");
</script>
</body>
</html>
值得一提的是,因為js弱型別,導致了傳入函式的引數個數可以沒有條件,從而導致函式沒有函式多載一說,JS也會對你傳入的資料個數進行調整,但傳入的數值個數比函式定義的數值個數小的話,傳入的數值會和函式定義的數值順序一一對應,但沒有對應的數值在函式的使用了的話,數值就會變成undefined,
例如,以下代碼,b數值沒有被傳入,就會被定義為undefined.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
//函式定義
test = function(a,b){
alert("傳入了:"+a+","+b);
}
//函式呼叫
test("hellojs");
</script>
</body>
</html>

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/305213.html
標籤:其他
下一篇:關于閉包的知識點
