javascript函數參數

來源:互聯網
上載者:User

標籤:參與   rip   color   沒有   直接   括弧   顯示   parameter   javascrip   

js函數參數有顯式參數(Parameters)即形參和隱式參數(Arguments)實參

1、顯式參數(Parameters)即形參在函數定義時列出。

function functionName(parameter1, parameter2, parameter3){    //要執行的代碼}

2、隱式參數(Arguments)即實參在函數調用時傳遞給函數的真正的值

function add(){    console.log(arguments[0], arguments[1], arguments[2]);}

參數的個數

(1)當實參比比函式宣告指定的形參個數少時,剩下的形參都將設定為undefined。

例:

function add(x, y){    console.log(x, y);}add(1);//1, undefined

(2)當實參比形參個數要多時,剩下的實參沒辦法直接獲得,可以通過arguments對象來訪問。在javascript中函數的參數在函數內部是用一個數組表示的。函數接收的始終都是這個數組,並不關心數組中包含哪些參數。而arguments是一個類數組對象,可以使用方括弧文法來訪問它的每一個元素。

例:

function add(x, y){    console.log(arguments[0], arguments[1], arguments[2]);}add(1, 2, 3);//1 2 3

arguments對象的length屬性可以顯示實參的個數,函數的length屬性則顯示形參的個數。

例:

function add(x, y){    console.log(arguments.length);//3}add(1, 2, 3);console.log(add.length);//2

形參可以提供便利,但不是必須的。

function add(){    console.log(arguments[0] + arguments[1]);}add(1, 2);//3

實參與形參同步

  當形參與實參個數相同時,arguments對象的值和對應形參的值保持同步,但命名空間獨立。

例:

function test(num1, num2){    console.log(num1, arguments[0]);//1 1    arguments[0] = 2;    console.log(num1, arguments[0]);//2 2    num1 = 10;    console.log(num1, arguments[0]);//10 10}test(1);

  在strict 模式下,arguments對象的值和形參都是獨立的。

例:

function test(num1, num2){    ‘use strict‘;    console.log(num1, arguments[0]);//1 1    argument[0] = 2;    comnsole.log(num1, arguments[0]);//1 2    num1 = 10;    console.log(num1, arguments[0]);//10 2}test(1);

  當形參並沒有對應的實參時,arguments對象的值與形參的值並不對應。

例:

function test(num1, num2){    console.log(num1, arguments[0]);//undefined, undefined    num1 = 10;    arguments[0] = 5;    console.log(num1, arguments[0]);//10, 5}test();

對象參數

  當一個函數包含超過3個形參時,要記住調用函數中實參的正確順序是一件很繁瑣的事情,可以通過值對的形式來傳入參數。

 

javascript函數參數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.