[英]Using the arguments object in functions
為什么foo函數可以正常工作。
function foo (a,b) {
return arguments.length;
}
但是,即使我在函數中傳遞了參數,boo函數返回的undefined不是函數。
function boo (a,b) {
return arguments.slice(0);
}
arguments
不是數組,而是類似數組的對象。 許多數組方法都對類似數組的對象起作用,因為它們希望對象具有數字屬性和length
屬性,例如arguments
。 您可以通過使用call
並將對象作為this
值傳遞來使用內置函數:
var args = Array.prototype.slice.call(arguments);
//^ args is a real array now
這也適用於其他方法,例如reduce
:
function sum(/*...args*/) {
return [].reduce.call(arguments, function(x, y){return x + y})
}
arguments
是一個對象,而不是 array
。 如果打印並看到,則可以看到一個對象:
function foo (a,b) {
console.log(arguments);
}
foo(10,20);
o/p: { '0': 10, '1': 20 }
從文檔中 ,
該對象包含每個傳遞給該函數的參數的條目,第一個條目的索引從0開始。例如,如果一個函數傳遞了三個參數,則可以按以下方式引用該參數:
arguments[0] arguments[1] arguments[2]
它沒有任何除外陣列屬性length
。
因此, return arguments.slice(0);
會失敗,因為slice
屬於array
的prototype
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.