Understanding of arguments (ES5) in js
1. Know arguments
①It exists in the function by default, which is an array-like object corresponding to the parameters passed to the function , (it looks like an array, and is essentially an object): arguments ②array-like means that it is not An array type, but an object type: but it has some characteristics of the array, such as length, and can be accessed through the index index; but it does not have some methods of the array, such as forEach, map, etc.;
function foo(num1, num2, num3) {
console.log(arguments);
//[Arguments] { '0': 10, '1': 20, '2': 30, '3': 40, '4': 50 }
// 常见的对arguments的操作是三个
// 1.获取参数的长度
console.log(arguments.length); //5
// 2.根据索引值获取某一个参数
console.log(arguments[2]); //30
console.log(arguments[3]); //40
console.log(arguments[4]); //50
// 3.callee获取当前arguments所在的函数
console.log(arguments.callee); //[Function: foo]函数自身
}
foo(10, 20, 30, 40, 50);
2. Convert arguments (object) into array (implement by yourself)
2.1. Realization of array slice method
// 额外补充的知识点: Array中的slice实现;
Array.prototype.hhslice = function (start, end) {
var arr = this;
start = start || 0;
end = end || arr.length;
var newArray = [];
for (var i = start; i < end; i++) {
newArray.push(arr[i]);
}
return newArray;
};
//测试:
//自己实现的slice方法
var newArray = Array.prototype.hhslice.call(["aaaa", "bbb", "cccc"]
,1, 3);
console.log(newArray); //[ 'bbb', 'cccc' ]
//系统中数组的slice方法
var names = ["aaa", "bbb", "ccc", "ddd"];
console.log(names.slice(1, 3)); //['bbb', 'ccc']
2.2. Convert arguments to array type by yourself
//自己实现arguments转成array类型
function foo(num1, num2) {
// 1.自己遍历arguments中所有的元素,并将每一个值扩大十倍
// var newArr = []
// for (var i = 0; i < arguments.length; i++) {
// newArr.push(arguments[i] * 10)
// }
// console.log(newArr) //[ 100, 200, 300, 400, 500 ]
// 2.Array.prototype.slice将arguments转成array
var newArr2 = Array.prototype.slice.call(arguments)
console.log(newArr2) //[ 10, 20, 30, 40, 50 ]
//或
var newArr3 = [].slice.call(arguments)
console.log(newArr3) //[ 10, 20, 30, 40, 50 ]
// 2.3.ES6的语法
var newArr4 = Array.from(arguments)
console.log(newArr4) //[ 10, 20, 30, 40, 50 ]
//或
var newArr5 = [...arguments]
console.log(newArr5) //[ 10, 20, 30, 40, 50 ]
}
foo(10, 20, 30, 40, 50)
3. Arrow functions do not bind arguments
①Arrow functions are not bound to arguments, so when we use arguments in an arrow function, we will go to the upper scope to find
②In the browser, arguments are not defined in the global object, and if they cannot be found, an error will be reported (arguments is not defined)
. In the node environment, the global object has defined arguments
// 1.案例一:
var foo = () => {
console.log(arguments);
};
foo();
// 在浏览器中,全局对象中没有定义arguments,会报错
// 在node环境中,全局对象有定义arguments
// 2.案例二:
function foo() {
var bar = () => {
console.log(arguments);
};
return bar;
}
var fn = foo(123);
fn(); //[Arguments] { '0': 123 } 在上层作用域中找到Arguments