posted 11/28/2010 by Raghav Khunger
Few days back a person asked on the forums on how to make a common JavaScript function for to add as many number as supplied in the arguments. I decided to write a blog on the solution which I gave to him. In JavaScript what ever arguments you supplied to the function is contained in the "arguments". I just run a loop over all the arguments and calculate the sum. Below is the sample code:
<html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script type="text/javascript"> function add() { var sum = 0; for (var i = 0, j = arguments.length; i < j; i++) { sum += arguments[i]; } return sum; } //Let's test it alert('Test 1: ' + add(1, 2, 3, 4, 5)); alert('Test 2: ' + add(1, 2, 3, 4, 5, 7, 9, 3, 4)); alert('Test 3: ' + add(1, 2)); alert('Test 4: ' + add(1, 2, 3, 4, 5, 6, 87, 87, 9, 5)); </script> </head> <body> <form id="form1" runat="server"> </form> </body> </html>
Do let me know your feedback, comments
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18