arguments

1.什麼是arguments:它是一個類數組對象,代表傳給一個function的參數列表。它的內容表示了函數執行時傳入函數的所有參數,可以用arguments[0],arguments[1]...來獲取單個參數。可以用arguments.length來獲取參數個數

         <script>
		function test(){
			console.log(arguments);
		}
		test('a','b',0,{foo:'hello arguments'});
	</script>
2.通常可以採用Array.prototype.slice.call(arguments);來將其轉換成數組,或者[].slice.call(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;
    };
}
但是我們可以這樣:
function getArgs() {
    const args = new Array(arguments.length);
    for(let i = 0; i < args.length; ++i) {
        args[i] = arguments[i];
    }
    return args;
}
3.修改它的值

它有隱藏的參數

window.onload = function(){
    abc(1,2,3);
}
function abc(x,y){
    alert(x+','+y);//1,2
	}
在嚴格模式下:
function test(a){
	"user strict";
	console.log(a,arguments[0]);//1,1
	a = 10;
	console.log(a,arguments[0]);//10,1
}
test(1);
在非嚴格模式下:
function test(a){
	console.log(a,arguments[0]);//1,1
	a = 10;
	console.log(a,arguments[0]);//10,10
}
test(1);

實現遞歸:

function add(n){
	if(n==1){
	return 1;
	}else{
	return n+arguments.callee(n-1);
	}
}
alert(add(3));
4.函數之間參數的傳遞

function test(a){
	b.apply(this,arguments);
}
function b(){
	console.log(arguments);//[1]
}
test(1);
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);//Method two
add(1, 2, 3);//Method two
but...
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);//Result is 3
add(1, 2, 3)//Result is 6
6.es6中的arguments

擴展操作符可以將 arguments 展開成獨立的參數。

function test(a){
	console.log(...arguments);
}
test(1,2,3);//1 2 3
7.類數組

我們可以自己創建一個類數組:

function Foo(){
}
Foo.prototype = Object.create(Array.prototype);
const foo = new Foo();
foo.push('a');
console.log(foo,foo.length);
此時的Foo示例擁有Array的所有方法,但是類型不是Array.








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