Javascript中arguments對象的詳解與使用方法_javascript技巧

來源:互聯網
上載者:User

一、arguments使用方法

通過方括弧文法訪問每一個元素

var fun = function(one) { console.log(arguments[0]); console.log(arguments[1]); console.log(arguments[2]);}fun(1, 2, 3)// 1// 2// 3

通過length屬性,查看到底要幾個參數

function fun() { return arguments.length;}fun(1, 2, 3) // 3fun(1) // 1fun() // 0

參數賦值(“strict 模式下不允許”)

var fun = function(a, b) { arguments[1] = 2; return a + b;}fun(1, 1)// 3

二、arguments與數組的關係

雖然arguments可以使用中括弧文法,並且具有length屬性,但arguments對象只是與數組類似,並不是Array的執行個體。因此,無法對 arguments 變數使用標準的數組方法,比如 push, pop 或者 slice。 雖然使用 for 迴圈遍曆也是可以的,但是為了更好的使用數組方法,最好把它轉化為一個真正的數組。

如何使用數組方法?

通過apply方法,把arguments作為參數傳進去,這樣就可以讓arguments使用數組方法了。

// 用於apply方法myFunction.apply(obj, arguments).// 使用與另一個數組合并Array.prototype.concat.apply([1,2,3], arguments)

終極解決方案,直接轉為真正的數組

下面的代碼將會建立一個新的數組,包含所有 arguments 對象中的元素。

var args = Array.prototype.slice.call(arguments);//或者var args = [];for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]);}//或者var args = [].slice.call(arguments, 0);

三、強大卻不建議使用的callee屬性

arguments的callee屬性可以調用函數本身,當函數正在執行時才可調用,可以實現方法的遞迴調用

下面的代碼將會實現一個求階乘方法

var factorial = function(x){ return x<=1?1:x*arguments.callee(x-1);}

在ECMAScript5strict 模式中,對這個屬性的讀寫操作會產生一個類型錯誤,並且會顯著的影響現代 JavaScript 引擎的效能,所以,因此強烈建議大家不要使用 arguments.callee 和它的屬性。

四、總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習和工作能帶來一定的協助,如果有疑問大家可以留言交流。

聯繫我們

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