A class Array
It contains a set of data and has a length property, but there is no way to Array. length values in the array of class objects can not be changed automatically.
二 arguments
arguments is an array object class. Representatives passed to a function parameter list.
function printArgs() {
console.log(arguments);
}
printArgs("A", "a", 0, { foo: "Hello, arguments" }); //["A", "a", 0, Object]
Look at the contents of arguments represented, which represents all the parameters passed to the function when the function is executed.
arguments.length means that the incoming number
Three arguments operation
1.arguments transfer array
- Array.prototype.slice.call(arguments);
- [].slice.call(arguments);
- Array.from()
2. Modify the arguments value
In strict mode, the function parameter arguments object without contact, a modification will not change the value of another. In non-strict mode, the two influence each other.
Strict mode:
function foo(a) {
"use strict";
console.log(a, arguments[0]); //1 1
a = 10;
console.log(a, arguments[0]); //10 1
arguments[0] = 20;
console.log(a, arguments[0]); //10 20
}
foo(1);
Non-strict mode:
function foo(a) {
console.log(a, arguments[0]); //1 1
a = 10;
console.log(a, arguments[0]); //10 10
arguments[0] = 20;
console.log(a, arguments[0]); //20 20
}
foo(1);
3. pass parameters from one function to another
function foo() {
bar.apply(this, arguments);
}
function bar(a, b, c) {
// logic
}
4. Extended operator
Extended operator can be expanded into a separate parameter arguments.
function func() {
console.log(...arguments);
}
func(1, 2, 3); // 1 2 3
The default parameters
The default parameter has no effect on the arguments
function func(firstArg = 0, secondArg = 1) {
console.log(arguments[0], arguments[1]); // 99 undefined
console.log(firstArg, secondArg); // 99 1
}
func(99);
Four Precautions
1.JS not override
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
2. arguments can not be a function of leak or pass out
The leak arguments object function out, the end result is a V8 engine will skip optimization, resulting in significant performance loss.
The following example is the arguments leaked:
// Leaking arguments example2:
function getArgs() {
const args = [].slice.call(arguments);
return args;
}
We can do this:
function getArgs() {
const args = new Array(arguments.length);
for(let i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
return args;
}