js Arguments對象筆記

1、概念

arguments 是一個對應於傳遞給函數的參數的類數組對象。
arguments對象是所有(非箭頭)函數中都可用的局部變量。你可以使用arguments對象在函數中引用函數的參數。

2、使用

arguments對象不是一個 Array。它類似於Array,但除了length屬性和索引元素之外沒有任何Array屬性。

function demo(a){
 console.log(arguments[0]);
}
demo(); //undefined
demo(1); //1

arguments對象可以轉換爲數組

var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);

// ES2015
const args = Array.from(arguments);   //使用Array.from()方法
const args = [...arguments];   //使用擴展運算符

3、屬性

arguments.callee   指向當前執行的函數。

arguments.caller (已廢棄)指向調用當前函數的函數。

arguments.length  指向傳遞給當前函數的參數數量。

arguments[@@iterator]   返回一個新的Array迭代器對象,該對象包含參數中每個索引的值。

4、剩餘參數、默認參數和解構賦值參數

嚴格模式下,剩餘參數、默認參數和解構賦值參數的存在不會改變 arguments對象的行爲

'use strict' //使用嚴格模式
function func(a) { 
  arguments[0] = 99; // updating arguments[0] does not also update a
  console.log(a);
}
func(10); // 10

function func(a) { 
  a = 99; // updating arguments[0] does not also update a
  console.log(a);
}
func(10); // 10

function func(a =50) { 
  arguments[0] = 99;
  console.log(a);
}
func(10); // 10

非嚴格模式中的函數沒有包含剩餘參數、默認參數和解構賦值參數,那麼arguments對象中的值跟蹤參數的值,同樣參數的值也會跟蹤arguments對象中的值

function func(a) { 
  arguments[0] = 99;   // 更新了arguments[0] 同樣更新了a
  console.log(a);
}
func(10); // 99

並且

function func(a) { 
  a = 99;              // 更新了a 同樣更新了arguments[0] 
  console.log(arguments[0]);
}
func(10); // 99

當非嚴格模式中的函數包含剩餘參數默認參數解構賦值,那麼arguments對象中的值不會跟蹤參數的值

function func(a = 55) { 
  arguments[0] = 99; // updating arguments[0] does not also update a
  console.log(a);
}
func(10); // 10

function func(a = 55) { 
  a = 99; // updating a does not also update arguments[0]
  console.log(arguments[0]);
}
func(10); // 10

function func(a = 55) { 
  console.log(arguments[0]);
}
func(); // undefined

5、參考鏈接

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章