Home >Web Front-end >JS Tutorial >Detailed explanation of arguments object in Javascript_Basic knowledge

Detailed explanation of arguments object in Javascript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:33:131077browse

In the previous article we discussed the default parameters in JavaScript. In this article, we will discuss the arguments parameter object of JavaScript.

For the function in the example below, how can we do different processing according to the different parameters passed in?

Copy code The code is as follows:

function addAll () {
// What do we do here?
}

// Should return 6
addAll(1, 2, 3);

// Should return 10
addAll(1, 2, 3, 4);

Fortunately, JavaScript has an arguments object that can handle the above situation. The arguments object is an array-like object. If you want to know more about the arguments object, please click here. We use the arguments object to change the above example:

Copy code The code is as follows:

function addAll () {
var sum = 0;

for (var i = 0; i < arguments.length; i ) {
        sum = arguments[i];
}

return sum;
}

// Returns 6
addAll(1, 2, 3);

// Returns 10
addAll(1, 2, 3, 4);

We said above that the arguments object is an array-like object, let’s test it:

Copy code The code is as follows:

function getName() {
console.log(Array.isArray(arguments));
}

//will output false
getName("benjamin");

The above test results can be seen:
It is not an array object, so what is the difference between it and an array object? Please click here for details.

Executing the following example will throw an error:

Copy code The code is as follows:

function sortArgs () {
// Uncaught TypeError: undefined is not a function
Sorted = arguments.sort()

return sorted;
}
sortArgs();

We can convert an array-like object into an array object as follows:

Copy code The code is as follows:

function sortArgs () {
// Convert arguments object into a real array
var args = [].slice.call(arguments);

// Now this will work!
Sorted = args.sort()

return sorted;
}

//will output [1, 2, 3]
console.log(sortArgs(1,3,2));

If you feel this article is helpful to you, I hope to forward it to more people who need it. If the article is inappropriate, please leave a message to correct it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn