W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
function functionName() { // function body // optional return; }
所有函數(shù)在JavaScript中返回一個值。在沒有顯式返回語句的情況下,函數(shù)返回undefined。
function myData() {
return 123;
}
console.log(myData()); // 123
function myValue() {
}
console.log(myValue()); // undefined
以下代碼顯示如何創(chuàng)建函數(shù):
function hello(name) {
console.log("hello " + name);
}
hello("CSS");
上面的代碼生成以下結(jié)果。
要在JavaScript中聲明函數(shù)的參數(shù),請將其列在括號中。在運行時沒有檢查這些參數(shù):
function hello(name) {
console.log("hello " + name);
}
hello();
hello("CSS", "HTML", "AAA", 4);
上面的代碼生成以下結(jié)果。
如果傳遞給函數(shù)調(diào)用的參數(shù)太少,則將為結(jié)果變量賦值undefined。如果傳入的太多,額外的會unused。所有函數(shù)在主體中都有一個預定義的數(shù)組,稱為 arguments
。它具有傳遞到函數(shù)的所有值,我們可以對參數(shù)列表進行額外的檢查。
JavaScript中的函數(shù)甚至不需要有名稱:
var x = function (a, b) {
return a + b;
}
console.log(x(10, 20));
上面的代碼生成以下結(jié)果。
無名函數(shù)通常稱為匿名函數(shù)。
每次調(diào)用函數(shù)時,都會創(chuàng)建一個新的變量作用域。在父作用域中聲明的變量可用于該函數(shù)。在新作用域中聲明的變量在函數(shù)退出時不可用。
參考下面的代碼:
var pet = "cat";
function myMethod() {
var pet = "dog";
console.log(pet);
}
myMethod();
console.log(pet);
上面的代碼生成以下結(jié)果。
將此作用域與匿名函數(shù)組合是更好的使用私有變量的方法,在匿名函數(shù)退出時私有變量將消失。
這里是一個計算錐體積的示例:
var height = 5;
var radius = 3;
var volume;
// declare and immediately call anonymous function to create scope
(function () {/*from w w w . j av a 2 s . c o m*/
var pir2 = Math.PI * radius * radius; // temp var
volume = (pir2 * height) / 3;
})();
console.log(volume);
上面的代碼生成以下結(jié)果。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: