• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Loop through parameters passed to a Javascript function

Loop through parameters passed to a Javascript function

I looked at how to set default values for parameters in a Javascript function the other day and in this post look at the arguments object which can be used to work out how many parameters were passed to a function and also to loop through each of them.

The arguments object in functions

The arguments object is a special property available within Javascript functions and behaves like an array. It has a length property and can be looped through like a regular array.

To check how many arguments or parameters were passed to a function check the length property. The following example simply writes out into the document the number of parameters passed:

function foo() {
    document.write(arguments.length + "<br />");
}

To test:

foo();
foo('apples');
foo('apples', 'bananas');
foo('apples', 'bananas', 'oranges');

And the output:

0
1
2
3

You could therefore do something based on the number of arguments passed to the function:

function foo() {
    if(arguments.length == 0) {
        // do something
    }
    else {
        // do something else
    }
}

Looping through the parameters

Looping through the arguments is just like looping through a regular array:

function foo() {
    for (var i = 0, j = arguments.length; i < j; i++){
        document.write(arguments[i]+' ');
    }
    document.write('<br />');
}

Using the same test as the earlier example above, the output would be:


apples
apples bananas 
apples bananas oranges

Check Out These Related posts:

  1. Type casting with PHP
  2. How to use letters and roman numerals instead of numbers in an HTML ordered list
  3. Fetch message parts into a flat array with PHP IMAP
  4. Setting default values for missing parameters in a Javascript function

Filed Under: Javascript

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap