RcBuilder@walla.com
call centre: 054-5614020

javascript arguments

26
Jan
2016
Posted by: RcBuilder  /   Category: Array / class / function / JAVASCRIPT / Object   /   No Comments

javascript arguments

The arguments object is an Array-like object, it’s a local variable available within all functions.
the arguments object is only similar to an array but not a real one and it doesn’t include any of the array functions except of length()
we can pass any parameters we’d like and it automatically pass them as an arguments object (no declaration required).
this technique is similar to the params object of C# !

slice the arguments to an array:

var args = Array.prototype.slice.call(arguments);
console.log(args);

concat the arguments to a string:

var args = Array.prototype.join.call(arguments);
console.log(args);

using:

function User(name, id) {
this.name = name;
this.id = id;
}

function fun() {
console.log(‘LENGTH : ‘ + arguments.length);
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);

if (arguments[i] instanceof User)
console.log(‘User :’ + arguments[i].id + ‘. ‘ + arguments[i].name);
}

}

/*
LENGTH : 3
red
orange
blue
*/
fun(‘red’, ‘orange’, ‘blue’);

/*
LENGTH : 2
200
500
*/
fun(200, 500);

/*
LENGTH : 1
[object Object]
*/
fun({ name: ‘Roby’, Age: 35 });

/*
LENGTH : 4
hello world
120
90.63
true
*/
fun(‘hello world’, 120, 90.63, true);

/*
LENGTH : 1
[object Object]
User :398. Avi
*/
fun(new User(‘Avi’, 398));

arguments and parameters:

there’s no problem to use both, arguments and parameters together,
the arguments always contains the full parameters list and the parameters will get their values corresponding to the sending values.
therefore, as we can see in the example below, the function ‘fun2′ expects only 2 parameters but we are supplying 3 of them
so the first 2 will pass to the ‘color1′ and ‘color2′ but the arguments object will contain all 3 parameters.

example:

function fun2(color1, color2) {
console.log(‘color1 : ‘ + color1);
console.log(‘color2 : ‘ + color2);

console.log(‘LENGTH : ‘ + arguments.length);
for (var i = 0; i < arguments.length; i++)
console.log(arguments[i]);
}

/*
color1 : red
color2 : orange
LENGTH : 3
red
orange
blue
*/
fun2(‘red’, ‘orange’, ‘blue’);

 

Author Avatar

About the Author

בניית אתרים ופתרונות טכנולוגים | RcBuilder

No Comments


  • פיתוח מערכות
  • פתרונות טכנולוגים
  • קידום אתרים
  • בניית אתרים