Key Takeaways
- arguments’ is a local, array-like object available inside every JavaScript function, containing all the arguments supplied to the function when it was called. It’s not a true array, as it doesn’t possess standard array methods like push and pop.
- Despite its limitations, ‘a(chǎn)rguments’ is a powerful tool, allowing the creation of flexible functions that accept a variable number of arguments, which can be converted to a real array using the Array method, slice.
- arguments’ also has a ‘callee’ property that contains a reference to the function that created the ‘a(chǎn)rguments’ object, enabling an anonymous function to refer to itself. This can be used to create self-referencing functions and functions with preset arguments.
arguments is the name of a local, array-like object available inside every function. It’s quirky, often ignored, but the source of much programming wizardry; all the major JavaScript libraries tap into the power of the arguments object. It’s something every JavaScript programmer should become familiar with.
Inside any function you can access it through the variable: arguments, and it contains an array of all the arguments that were supplied to the function when it was called. It’s not actually a JavaScript array; typeof arguments will return the value: "object". You can access the individual argument values through an array index, and it has a length property like other arrays, but it doesn’t have the standard Array methods like push and pop.
Create Flexible Functions
Even though it may appear limited, arguments is a very useful object. For example, you can make functions that accept a variable number of arguments. The format function, found in the base2 library by Dean Edwards, demonstrates this flexibility:
function format(string) { var args = arguments; var pattern = new RegExp("%([1-" + arguments.length + "])", "g"); return String(string).replace(pattern, function(match, index) { return args[index]; }); };
You supply a template string, in which you add place-holders for values using %1 to %9, and then supply up to 9 other arguments which represent the strings to insert. For example:
format("And the %1 want to know whose %2 you %3", "papers", "shirt", "wear");
The above code will return the string "And the papers want to know whose shirt you wear".
One thing you may have noticed is that, in the function definition for format, we only specified one argument: string. JavaScript allows us to pass any number of arguments to a function, regardless of the function definition, and the arguments object has access to all of them.
Convert it to a Real Array
Even though arguments is not an actual JavaScript array we can easily convert it to one by using the standard Array method, slice, like this:
var args = Array.prototype.slice.call(arguments);
The variable args will now contain a proper JavaScript Array object containing all the values from the arguments object.
Create Functions with Preset Arguments
The arguments object allows us to perform all sorts of JavaScript tricks. Here is the definition for the makeFunc function. This function allows you to supply a function reference and any number of arguments for that function. It will return an anonymous function that calls the function you specified, and supplies the preset arguments together with any new arguments supplied when the anonymous function is called:
function format(string) { var args = arguments; var pattern = new RegExp("%([1-" + arguments.length + "])", "g"); return String(string).replace(pattern, function(match, index) { return args[index]; }); };
The first argument supplied to makeFunc is considered to be a reference to the function you wish to call (yes, there’s no error checking in this simple example) and it’s removed from the arguments array. makeFunc then returns an anonymous function that uses the apply method of the Function object to call the function specified.
The first argument for apply refers to the scope the function will be called in; basically what the keyword this will refer to inside the function being called. That’s a little advanced for now, so we just keep it null. The second argument is an array of values that will be converted into the arguments object for the function. makeFunc concatenates the original array of values onto the array of arguments supplied to the anonymous function and supplies this to the called function.
Lets say there was a message you needed to output where the template was always the same. To save you from always having to quote the template every time you called the format function you could use the makeFunc utility function to return a function that will call format for you and fill in the template argument automatically:
format("And the %1 want to know whose %2 you %3", "papers", "shirt", "wear");
You can call the majorTom function repeatedly like this:
var args = Array.prototype.slice.call(arguments);
Each time you call the majorTom function it calls the format function with the first argument, the template, already filled in. The above calls return:
function makeFunc() { var args = Array.prototype.slice.call(arguments); var func = args.shift(); return function() { return func.apply(null, args.concat(Array.prototype.slice.call(arguments))); }; }
Create Self-referencing Functions
You may think that’s pretty cool, but wait, arguments has one more surprise; it has another useful property: callee. arguments.callee contains a reference to the function that created the arguments object. How can we use such a thing? arguments.callee is a handy way an anonymous function can refer to itself.
var majorTom = makeFunc(format, "This is Major Tom to ground control. I'm %1.");
majorTom("stepping through the door"); majorTom("floating in a most peculiar way");
"This is Major Tom to ground control. I'm stepping through the door." "This is Major Tom to ground control. I'm floating in a most peculiar way."
repeat is a function that takes a function reference, and 2 numbers. The first number is how many times to call the function and the second represents the delay, in milliseconds, between each call. Here's the definition for repeat:
However, I want to create a special version of that function that repeats 3 times with a delay of 2 seconds between each time. With my repeat function, I can do this:
function repeat(fn, times, delay) { return function() { if(times-- > 0) { fn.apply(null, arguments); var args = Array.prototype.slice.call(arguments); var self = arguments.callee; setTimeout(function(){self.apply(null,args)}, delay); } }; }
The result of calling the somethingWrong function is an alert box repeated 3 times with a 2 second delay between each alert.
function format(string) { var args = arguments; var pattern = new RegExp("%([1-" + arguments.length + "])", "g"); return String(string).replace(pattern, function(match, index) { return args[index]; }); };
Frequently Asked Questions about JavaScript Arguments
What is the ‘a(chǎn)rguments’ object in JavaScript?
The ‘a(chǎn)rguments’ object is a local variable available within all non-arrow functions in JavaScript. It contains an array-like structure with all the arguments passed to the function. This object is useful when a function needs to handle variable numbers of arguments. It’s important to note that the ‘a(chǎn)rguments’ object is not an actual array, but it can be converted to one if needed.
How can I convert the ‘a(chǎn)rguments’ object into an array?
Although the ‘a(chǎn)rguments’ object behaves like an array, it does not inherit from the Array prototype, so array methods cannot be directly applied to it. However, you can convert it into an array using the Array.from() method or the spread operator (…). Here’s an example:
function convertArgsToArray() {
var argsArray = Array.from(arguments);
// or
var argsArray = [...arguments];
}
Can I use the ‘a(chǎn)rguments’ object in arrow functions?
No, the ‘a(chǎn)rguments’ object is not available within arrow functions. Arrow functions do not have their own ‘a(chǎn)rguments’ object. However, they can access the ‘a(chǎn)rguments’ object from the nearest non-arrow parent function.
What is the ‘typeof’ operator in JavaScript?
The ‘typeof’ operator in JavaScript is used to determine the data type of a given value or variable. It returns a string indicating the type of the unevaluated operand. For example, ‘typeof 3’ will return ‘number’, and ‘typeof “hello”‘ will return ‘string’.
How can I use ‘typeof’ with ‘a(chǎn)rguments’ in JavaScript?
You can use the ‘typeof’ operator to check the type of each argument passed to a function. Here’s an example:
function checkArgsType() {
for (var i = 0; i console.log(typeof arguments[i]);
}
}
What does ‘a(chǎn)rguments[0]’ mean in JavaScript?
arguments[0]’ refers to the first argument passed to a function. Similarly, ‘a(chǎn)rguments[1]’ refers to the second argument, and so on. If no arguments are passed, ‘a(chǎn)rguments[0]’ will be ‘undefined’.
Can I modify the ‘a(chǎn)rguments’ object in JavaScript?
Yes, you can modify the ‘a(chǎn)rguments’ object in non-strict mode. However, it’s generally not recommended because it can lead to confusing and hard-to-debug code. In strict mode, any attempt to modify the ‘a(chǎn)rguments’ object will throw an error.
What is the length property of the ‘a(chǎn)rguments’ object?
The length property of the ‘a(chǎn)rguments’ object returns the number of arguments that were passed to the function. It’s useful when you need to iterate over the arguments or determine how many arguments were passed.
Can I use the ‘a(chǎn)rguments’ object with default parameters in JavaScript?
Yes, but with a caveat. If a function with default parameters is called with fewer arguments than there are parameters, the ‘a(chǎn)rguments’ object will only contain the actual arguments passed, not the default values.
What is the ‘callee’ property of the ‘a(chǎn)rguments’ object?
The ‘callee’ property of the ‘a(chǎn)rguments’ object is a reference to the currently executing function. This property is deprecated and should not be used in new code. Instead, you can use named function expressions or arrow functions.
The above is the detailed content of arguments: A JavaScript Oddity. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

To write clean and maintainable JavaScript code, the following four points should be followed: 1. Use clear and consistent naming specifications, variable names are used with nouns such as count, function names are started with verbs such as fetchData(), and class names are used with PascalCase such as UserProfile; 2. Avoid excessively long functions and side effects, each function only does one thing, such as splitting update user information into formatUser, saveUser and renderUser; 3. Use modularity and componentization reasonably, such as splitting the page into UserProfile, UserStats and other widgets in React; 4. Write comments and documents until the time, focusing on explaining the key logic and algorithm selection

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.
