JavaScript arguments類數組

來源:互聯網
上載者:User

標籤:索引值   type   模式   ict   span   改變   src   數組   表示   

1. 什麼是類數組

  arguments 是一個類數組對象。代表傳給一個function的參數列表。

   我們來傳一個執行個體。

 function printArgs() {

     console.log(arguments);

   }

   printArgs("A", "a", 0, { foo: "Hello, arguments" });

 // ["A", "a", 0, Object]

 再看看 arguments 表示的內容,其表示了函數執行時傳入函數的所有參數。在上面的例子中,代表了傳入 printArgs 函數中的四個參數,可以分別用 arguments[0]、 arguments[1]… 來擷取單個的參數。

 

2. arguments 的操作

 arguments.length

    arguments 是個類數組對象,其包含一個 length 屬性,可以用 arguments.length 來獲得傳入函數的參數個數。

   arguments 轉數組。

    Array.prototype.silce.call(arguments);  // 或者使用  [].slice.call(arguments);

   修改 arguments 值。

  function foo(a) {

      "use strict";

      console.log(a, arguments[0]);

      a = 10;

      console.log(a, arguments[0]);

      arguments[0] = 20;

      console.log(a, arguments[0]);

  }

  foo(1);

  // 1 1    //10 1    //10 20

  非strict 模式的例子:

  function foo(a) {

 

      console.log(a, arguments[0]);

 

      a = 10;

 

      console.log(a, arguments[0]);

 

      arguments[0] = 20;

 

      console.log(a, arguments[0]);

 

  }

 

  foo(1);

  // 1 1    //10 10     //20 20

  在strict 模式下,函數中的參數與 arguments 對象沒有聯絡,修改一個值不會改變另一個值。而在非strict 模式下,兩個會互相影響。

 

3.  數組與類數組對象

  數組具有一個基本特徵:索引。這是一般對象所沒有的。

const obj = { 0: "a", 1: "b" };

const arr = [ "a", "b" ];

  我們利用 obj[0]、arr[0] 都能取得自己想要的資料,但取得資料的方式確實不同的。obj[0] 是利用對象的索引值對存取資料,而arr[0] 卻是利用數組的索引。事實上,Object 與 Array 的唯一區別就是 Object 的屬性是 string,而   Array 的索引是 number。

  下面看看類數組對象。

  偽數組的特性就是長得像數組,包含一組資料以及擁有一個 length 屬性,但是沒有任何 Array 的方法。再具體的說,length 屬性是個非負整數,上限是 JavaScript 中能精確表達的最大數字;另外,類數組對象的 length 值無法自動改變。

  

JavaScript arguments類數組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.