為什么說arguments是偽(類)數組?
答:因為arguments它不是數組,卻用起來像數組,有length屬性和[ ]訪問成員。但是不具有數據的方法,如join()
、concat()
等。。。
怎樣將arguments轉換成數組
Array.prototype.slice.apply(arguments)
image.png
轉換前
image.png
轉換后
image.png
1、數組長度
window.onload = function(){
function abc(){
console.log(arguments.length)
}
abc(1,2,3)
}// 3
2、改變參數值
window.onload = function(){
function abc(x,y,z){
arguments[2] = "hello";
for(var i=0;i<=arguments.length;i++){
console.log(" "+arguments[i]);
}
}
abc(1,2,3)
}// 1,2,hello
3、遞歸(callee()
調用自身)
求1到n的自然數之和
function add(x){
if(x == 1) return 1;
else return x + arguments.callee(x-1);
}
console.log(add(5))//15
對于沒有命名的函數
var result = function(x){
if(x == 1) return 1;
return x+arguments.callee(x-1);
}
console.log(result(5))//15