JavaScript arguments 對象全面介紹

rabikta5016 8年前發布 | 6K 次閱讀 JavaScript開發 JavaScript

1. 什么是 arguments

MDN 上解釋:

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

我們先用一個例子直觀了解下 JavaScript 中的 arguments 長什么樣子。

function printArgs() {
    console.log(arguments);
}

printArgs("A", "a", 0, { foo: "Hello, arguments" });</code></pre>

執行結果是:

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

乍一看,結果是個數組,但并不是真正的數組,所以說 arguments 是一個類數組的對象(想了解真正數組與類數組對象的區別可以一直翻到最后)。

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

2. arguments 操作

2.1 arguments length

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

function func() {
    console.log("The number of parameters is " + arguments.length);
}

func(); func(1, 2); func(1, 2, 3);</code></pre>

執行結果如下:

The number of parameters is 0
The number of parameters is 2
The number of parameters is 3

2.2 arguments 轉數組

通常使用下面的方法來將 arguments 轉換成數組:

Array.prototype.slice.call(arguments);

還有一個更簡短的寫法:

[].slice.call(arguments);

在這里,只是簡單地調用了空數組的 slice 方法,而沒有從 Array 的原型層面調用。

為什么上面兩種方法可以轉換呢?

首先,slice 方法得到的結果是一個數組,參數便是 arguments。事實上,滿足一定條件的對象都能被 slice 方法轉換成數組。看個例子:

const obj = { 0: "A", 1: "B", length: 2 };
const result = [].slice.call(obj);
console.log(Array.isArray(result), result);

執行結果是:

true ["A", "B"]

從上面例子可以看出,條件就是: 1) 屬性為 0,1,2...;2) 具有 length 屬性;

另外,有一個需要注意的地方就是, 不能將函數的 arguments 泄露或者傳遞出去 。什么意思呢?看下面的幾個泄露 arguments 的例子:

// Leaking arguments example1:
function getArgs() {
    return arguments;
}

// Leaking arguments example2: function getArgs() { const args = [].slice.call(arguments); return args; }

// Leaking arguments example3: function getArgs() { const args = arguments; return function() { return args; }; }</code></pre>

上面的做法就直接將函數的 arguments 對象泄露出去了,最終的結果就是 V8 引擎將會跳過優化,導致相當大的性能損失。

你可以這么做:

function getArgs() {
    const args = new Array(arguments.length);
    for(let i = 0; i < args.length; ++i) {
        args[i] = arguments[i];
    }
    return args;
}

那就很好奇了,我們每次使用 arguments 時通常第一步都會將其轉換為數組,同時 arguments 使用不當還容易導致性能損失,那么為什么不將 arguments 直接設計成數組對象呢?

這需要從這門語言的一開始說起。arguments 在語言的早期就引入了,當時的 Array 對象具有 4 個方法: toString、 join、 reverse 和 sort。arguments 繼承于 Object 的很大原因是不需要這四個方法。而現在,Array 添加了很多強大的方法,比如 forEach、map、filter 等等。那為什么現在不在新的版本里讓 arguments 重新繼承自 Array呢?其實 ES5 的草案中就包含這一點,但為了向前兼容,最終還是被委員會否決了。

2.3 修改 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);

輸出:

另一個非嚴格模式的例子:

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);

輸出結果為:

從上面的兩個例子中可以看出,在嚴格模式下,函數中的參數與 arguments 對象沒有聯系,修改一個值不會改變另一個值。而在非嚴格模式下,兩個會互相影響。

2.4 將參數從一個函數傳遞到另一個函數

下面是將參數從一個函數傳遞到另一個函數的推薦做法。

function foo() {
    bar.apply(this, arguments);
}
function bar(a, b, c) {
    // logic
}

2.5 arguments 與重載

很多語言中都有重載,但 JavaScript 中沒有。先看個例子:

function add(num1, num2) {
    console.log("Method one");
    return num1 + num2;
}

function add(num1, num2, num3) { console.log("Method two"); return num1 + num2 + num3; }

add(1, 2); add(1, 2, 3);</code></pre>

執行結果為:

Method two
Method two

所以,JavaScript 中,函數并沒有根據參數的不同而產生不同的調用。

是不是 JavaScript 中就沒有重載了呢?并不是,我們可以利用 arguments 模擬重載。還是上面的例子。

function add(num1, num2, num3) {
    if (arguments.length === 2) {
        console.log("Result is " + (num1 + num2));
    }
    else if (arguments.length === 3) {
        console.log("Result is " + (num1 + num2 + num3));
    }
}

add(1, 2); add(1, 2, 3)</code></pre>

執行結果如下:

Result is 3
Result is 6

3. ES6 中的 arguments

3.1 擴展操作符

直接上栗子:

function func() {
    console.log(...arguments);
}

func(1, 2, 3);</code></pre>

執行結果是:

簡潔地講,擴展操作符可以將 arguments 展開成獨立的參數。

3.2 Rest 參數

還是上栗子:

function func(firstArg, ...restArgs) {
    console.log(Array.isArray(restArgs));
    console.log(firstArg, restArgs);
}

func(1, 2, 3);</code></pre>

執行結果是:

true
1 [2, 3]

從上面的結果可以看出,Rest 參數表示除了明確指定剩下的參數集合,類型是 Array。

3.3 默認參數

栗子:

function func(firstArg = 0, secondArg = 1) {
    console.log(arguments[0], arguments[1]);
    console.log(firstArg, secondArg);
}

func(99);</code></pre>

執行結果是:

99 undefined
99 1

可見,默認參數對 arguments 沒有影響,arguments 還是僅僅表示調用函數時所傳入的所有參數。

3.4 arguments 轉數組

Array.from() 是個非常推薦的方法,其可以將所有類數組對象轉換成數組。

4. 數組與類數組對象

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

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 值無法自動改變。

如何自己創建一個類數組對象?

function Foo() {}
Foo.prototype = Object.create(Array.prototype);

const foo = new Foo(); foo.push('A'); console.log(foo, foo.length); console.log("foo is an array? " + Array.isArray(foo));</code></pre>

執行結果是:

["A"] 1
foo is an array? false

也就是說 Foo 的示例擁有 Array 的所有方法,但類型不是 Array。

如果不需要 Array 的所有方法,只需要部分怎么辦呢?

function Bar() {}
Bar.prototype.push = Array.prototype.push;

const bar = new Bar(); bar.push('A'); bar.push('B'); console.log(bar);</code></pre>

執行結果是:

Bar {0: "A", 1: "B", length: 2}

參考:

  1. JavaScript中的數組與偽數組的區別

  2. MDN arguments

  3. Avoid modifying or passing arguments into other functions — it kills optimization

  4. Optimization killers

  5. Why isn't a function's arguments object an array in Javascript?

  6. arguments 對象

  7. Advanced Javascript: Objects, Arrays, and Array-Like objects

  8. JavaScript 特殊對象 Array-Like Objects 詳解

  9. What is a good way create a Javascript array-like object?

 

來自:https://segmentfault.com/a/1190000007091243

 

 本文由用戶 rabikta5016 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!