DIV CSS 佈局教程網

JavaScript 函式參數的用法解析
編輯:關於JavaScript     

本文記錄了關於函式參數的學習筆記,供大家備忘參考。

函式的參數

JavaScript 不會對參數值進行型別檢查,任何型別的值都能傳入。若傳入的參數過少,缺少的參數值為 undefined;若過多,多餘的會被忽略。

 function add(num1, num2) {
 return num1 + num2;
 }
 console.info(add(1, 2)); //3
 console.info(add("1", 2)); //12(不檢查型別,字串與數字可混用)
 console.info(add(1, 2, 3)); //3(多餘參數被忽略)
 console.info(add(1)); //NaN(缺少的參數視為 undefined)

檢測參數是否缺失

 function sayHello(name, message) {
 if (typeof message === 'undefined') {
 message = '你好!';
 }
 console.info(name + "," + message);
 }
 sayHello("賈君鵬", "你媽喊你吃飯");
 sayHello("賈君鵬"); //賈君鵬,你好!

保存參數的 arguments 物件

利用 arguments 物件,可以寫出支援任意個參數的函式。arguments 看似陣列,實際上並非陣列,因此無法使用多數陣列方法。

 function sumNumbers() {
 var result = 0;
 for (var i = 0; i < arguments.length; i++) {
 result += arguments[i];
 }
 return result;
 }
 console.info(sumNumbers(1, 2)); //3
 console.info(sumNumbers(1, 2, 3)); //6

函式物件的 length 屬性

arguments.length // 函式接收的實參個數
函式名.length // 函式定義的形參個數

 function sayName(name) { console.info(name); }
 function sum(num1, num2) { return num1 + num2; }
 function sayHi() { console.info("hi"); }
 console.info(sayName.length); //1
 console.info(sum.length); //2
 console.info(sayHi.length); //0

作為參數的函式物件

函式是物件,可以作為另一個函式的參數。

 function callSomeFunction(func, argu) {
 return func(argu);
 }
 function getGreeting(name) {
 return "Hello, " + name;
 }
 var result = callSomeFunction(getGreeting, "jxl");
 console.info(result); //Hello,jxl

使用命名或匿名函式作為參數:

 var callTwice = function (otherFunc) {
 otherFunc();
 otherFunc();
 };
 callTwice(function () {
 console.info("this is a function");
 });

函式作為參數的實例(例如為按鈕綁定點擊事件):

 var button = document.getElementById('btnClick');
 var result = document.getElementById('result');
 var clickCount = 0;
 button.addEventListener('click', function () {
 clickCount++;
 result.setAttribute('value', clickCount + ': Hello,world!');
 });

以上就是 JavaScript 函式參數的完整解析,希望對大家有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved