The use of arguments in JavaScript

Source: Internet
Author: User

function Add (n1,n2) {
return n1+n2;
}
function Add (n1,n2,n3) {
return n1+n2+n3;
}
alert (add); The//nan,js method uses the nearest principle, and since the method does not pass in N3, the result is NaN

JS there is no method overload, how to solve the above problem?


//arguments
Function F1 () {
var sum=0;
for (Var i=0;i<arguments.length;i++) {
Sum+=arguments[i];
}
return sum;
}
Alert (F1 (1,2,3,4,5));


Using arguments, the calculation of chestnuts plus numbers and
function ff (name) {
var sum=0;
for (Var i=1;i<arguments.length;i++) {
Sum+=arguments[i];
}
return arguments[0]+sum;
}
Alert (FF (' chestnut ', 1,2,3,4,5));//Chestnut 15

Name, age
function test (name,age) {
if (!age) {//age No parameter is passed, age is undefined
age=18;
}
Alert (' The name is ' +name+ ' age is ' +age ');
}
Test (' Xiao Ming ');//name is Xiaoming age is 18

The use of arguments in JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.