Переклад не закінчено. Будь ласка, допоможіть перекласти цю статтю з англійської.
Об'єкт arguments це масиво-подібний об'єкт, що аналогічний аргументам, які були передані в функцію.
Синтакс
arguments
Опис
Об'єкт arguments - це локальна змінна, яка доступна всередині всіх функцій. Ви можете звернутися до аргументів функції всередині даної функції використовуючи об'єкт arguments. Цей об'єкт містить всі аргументи, які були передані функції, індекс першого переданого аргументу починається з 0. Для прикладу, якщо в функцію передано три аргументи, то ви можете звернутися до них як:
arguments[0] arguments[1] arguments[2]
Аргументи також можуть бути встановлені як:
arguments[1] = 'new value';
Об'єкт arguments не є масивом (Array). Він подібний до масиву, але не має жодних властивостей масиву, крім довжини(length). Наприклад, він не має методу pop. Проте він може бути перероблений в справжній масив:
var args = Array.prototype.slice.call(arguments); var args = [].slice.call(arguments);
Ви також можете використати Array.from() метод або spread operator, щоб переробити arguments в справжній масив:
var args = Array.from(arguments); var args = [...arguments];
Using slice on arguments prevents optimizations in some JavaScript engines (V8 for example - more information). If you care for them, try constructing a new array by iterating through the arguments object instead. An alternative would be to use the despised Array constructor as a function:
var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));
Ви можете використовувати об'єкт arguments коли викликаєте функцію з більшою кількістю аргументів ніж формально оголошено приймати. Цей підхід є корисним для функцій, в які може бути передано різна кількість аргументів. Використовуйте arguments.length щоб визначити кількість аргументів, які були передані в функцію, і тоді обробляти кожен аргумент використовуючи об'єкт arguments. Щоб визначити кількість параметрів в сигнатурі(signature) функції, використовуйте параметр Function.length.
The typeof arguments returns 'object'.
console.log(typeof arguments); // 'object'
The typeof individual arguments can be determined with the use of indexing.
console.log(typeof arguments[0]); //this will return the typeof individual arguments.
Properties
arguments.callee- Reference to the currently executing function.
arguments.caller- Reference to the function that invoked the currently executing function.
arguments.length- Reference to the number of arguments passed to the function.
arguments[@@iterator]- Returns a new Array Iterator object that contains the values for each index in the arguments.
Examples
Defining a function that concatenates several strings
This example defines a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:
function myConcat(separator) {
var args = Array.prototype.slice.call(arguments, 1);
return args.join(separator);
}
You can pass any number of arguments to this function, and it creates a list using each argument as an item in the list.
// returns "red, orange, blue"
myConcat(", ", "red", "orange", "blue");
// returns "elephant; giraffe; lion; cheetah"
myConcat("; ", "elephant", "giraffe", "lion", "cheetah");
// returns "sage. basil. oregano. pepper. parsley"
myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");
Defining a function that creates HTML lists
This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is "u" if the list is to be unordered (bulleted), or "o" if the list is to be ordered (numbered). The function is defined as follows:
function list(type) {
var result = "<" + type + "l><li>";
var args = Array.prototype.slice.call(arguments, 1);
result += args.join("</li><li>");
result += "</li></" + type + "l>"; // end list
return result;
}
You can pass any number of arguments to this function, and it adds each argument as an item to a list of the type indicated. For example:
var listHTML = list("u", "One", "Two", "Three");
/* listHTML is:
"<ul><li>One</li><li>Two</li><li>Three</li></ul>"
*/
Rest, default and destructured parameters
The arguments object can be used in conjunction with rest parameters, default parameters or destructured parameters.
function foo(...args) {
return arguments;
}
foo(1, 2, 3); // { "0": 1, "1": 2, "2": 3 }
However, in non-strict functions, a mapped arguments object is only provided if the function does not contain any rest parameters, any default parameters or any destructured parameters. For example, in the following function that uses a default parameter, 10 instead of 100 is returned:
function bar(a=1) {
arguments[0] = 100;
return a;
}
bar(10); // 10
In this example, where there are no rest parameters, any default parameters or any destructured parameters, 100 is returned:
function zoo(a) {
arguments[0] = 100;
return a;
}
zoo(10); // 100
Actually if there are no rest parameters, any default parameters or any destructured parameters, the formal arguments will refer the arguments object's latest values, when the formal arguments value needs to be read then arguments latest data will be read, and when formal arguments value changes, arguments will also be updated. See the code below:
function func(a, b) {
arguments[0] = 90;
arguments[1] = 99;
console.log(a + ", " + b);
}
func(1, 2); // 90, 99
or,
function func(a, b) {
a = 9;
b = 99;
console.log(arguments[0] + ", " + arguments[1]);
}
func(3, 4); // 9, 99
But if rest parameters, or any default parameters or any destructured parameters are present, then normal behaviour like default parameters will be proccessed. See,
function func(a, b, c=9) {
arguments[0] = 99;
arguments[1] = 98;
console.log(a + ", " + b);
}
func(3, 4); // 3, 4
Specifications
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 1st Edition (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.1 |
| ECMAScript 5.1 (ECMA-262) The definition of 'Arguments Object' in that specification. |
Standard | |
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Arguments Exotic Objects' in that specification. |
Standard | |
| ECMAScript 2017 Draft (ECMA-262) The definition of 'Arguments Exotic Objects' in that specification. |
Draft |
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |

