Example Analysis of arguments usage in Javascript and arguments instance analysis

Source: Internet
Author: User

Example Analysis of arguments usage in Javascript and arguments instance analysis

This example describes how to use arguments in Javascript. Share it with you for your reference. The specific analysis is as follows:

Let's take a look at the following example:

Function add (n1, n2) {return n1 + n2;} function add (n1, n2, n3) {return n1 + n2 + n3;} alert (add (1, 2 )); // NaN, the method called in js adopts the proximity principle; // The result is NaN because the method is not passed in n3.

Js does not support method overloading. How can this problem be solved?

// 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); // use arguments, in the calculation example, add the number and function ff (name) {var sum = 0; for (var I = 1; I <arguments. length; I ++) {sum + = arguments [I];} return arguments [0] + sum;} alert (ff ('example ', 1, 2, 3, 4, 5); // example 15 // name, age function test (name, age) {if (! Age) {// age when no parameter is passed, age is undefined age = 18;} alert ('name is '+ name +' age is '+ age );} test ('James '); // The name is James. The age is 18.

I hope this article will help you design javascript programs.

Related Article

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.