Online Documentation Server
 ПОИСК
ods.com.ua Web
 КАТЕГОРИИ
Home
Programming
Net technology
Unixes
Security
RFC, HOWTO
Web technology
Data bases
Other docs

 


 ПОДПИСКА

 О КОПИРАЙТАХ
Вся предоставленная на этом сервере информация собрана нами из разных источников. Если Вам кажется, что публикация каких-то документов нарушает чьи-либо авторские права, сообщите нам об этом.




Previous Table of Contents Next

The parameter is assigned its default value only if the function is called without specifying the required argument. The following function uses this technique to print a row of a given character with an asterisk as the default character, and 30 characters as the default length:

function checkDefault(parameter, defaultValue) {
  if (typeof parameter == "undefined")
 return defaultValue
  /* else */
 return parameter
}

function drawLine(character, numOfChars) {
  character = checkDefault(character, "*")
  numOfChars = checkDefault(numOfChars, 30)
  for (var i = 0; i < numOfChars; i++) {
 document.write(character)
  }
}

Here are some function calls and their corresponding output:

drawLine() // prints 30 asterisks

******************************

drawLine("=") // prints 30 equal signs

=============================================

drawLine("-", 10) // prints 10 dashes

----------

It is also possible to specify the second argument without providing the first, using an undefined variable (just declare it before with var, without initializing it).


Caution:  Be aware that the preceding checkDefault() function is not compatible with Netscape Navigator 2.0x or Microsoft Internet Explorer 3.0x, because they do not support the typeof operator. Use the arguments array to simulate C++’s default arguments feature. The previous drawLine() function would then be as follows:

function drawLine(character, numOfChars) {
   args = drawLine.arguments
   if (args.length < 1)
 character = "*"
   if (args.length < 2)
 numOfChars = 30

   for (var i = 0; i < numOfChars; i++) {
  document.write(character)
   }
}

If the function receives no arguments, the value of character is set to the default “*”. If the function received one argument or less, the parameter numOfChars defaults to 30. Because this function uses the arguments array, named parameters are not necessary—you can use the array instead as in the following function definition:

function drawLine() {
   args = drawLine.arguments
   if (args.length < 1)
  args[0] = "*"
   if (args.length < 2)
  args[1] = 30

   for (var i = 0; i < args[1]; i++) {
  document.write(args[0])
   }
}

Returning a Value

A function can return a value, so it is possible to use a function call as a valid JavaScript value. Use this feature to create general functions for usage by other scripts. For example, you can use a function that accepts a number in one base and returns it in a different representation. This function can be used in creating a base-conversion table, a dialog box, or additional calculations.

Use the following syntax to return a value from within a function:

return value

The return statement returns a value and terminates the function, similarly to the way break terminates a loop. Take a look at the following function:

function sum(op1, op2) {
  return op1 + op2
}

var answer = sum(3, 5)
alert(answer)

The value returned by the function is the sum of its arguments. As you can see, the function evaluates to a value. A function may only return one value—either a variable, a literal, or any other valid data structure.

A function with a return value can also generate an output. When you use the function in an expression, it automatically runs, executing all statements until it returns a value that is used in the expression. The preceding function can also display the sum of its arguments inside the function itself, provided that the alert() statement precedes the return statement (which terminates the function):

function sum(op1, op2) {
  var result = op1 + op2
  alert(result)
  return result
}
var answer = sum(3, 5)

Be sure that the return statement is placed after the statements that should be executed, because it terminates the function, and no additional statements of the function are executed afterwards.

You can use nested if constructions without else statements, provided that each if statement calls a return statement, if the condition is true. Eliminating the else statements does not affect the efficiency of the function, because the function terminates immediately after a true condition is met. The following function converts hexadecimal digits (not numbers) to their equivalent decimal values:

function getValue(dig) {
  if (dig == "A") return 10
  if (dig == "B") return 11
  if (dig == "C") return 12
  if (dig == "D") return 13
  if (dig == "E") return 14
  if (dig == "F") return 15
  return dig
  // the return statement terminates the function,
  // so there is no need for else statements
}

If the digit is between 0 and 9, none of the conditions evaluate to true, so the function returns the same digit it accepts:

return dig

Recursion

A recursive function is usually one that calls itself. It is similar to a loop with or without a terminating condition. Some programming functions lend themselves to recursive algorithms, such as the factorial one. The factorial is a classic recursive algorithm, because it is very obvious. A simple mathematical definition of the factorial operation is:

fact(0) = 1
fact(n) = n * fact(n–1)

Factorial is commonly represented by the exclamation mark (!).

With this algorithm, let’s calculate 3!:

  1. fact(3) = 3 * fact(2)
  2. fact(2) = 2 * fact(1)
  3. fact(1) = 1 * fact(0)
  4. fact(0) = 1

As you can see, the algorithm works its way down from the given number to zero, so when it gets to fact(0) it must work its way back up to the numbers:

We know that fact(0) = 1.

fact(1) = 1 * fact(0) = 1 * 1 = 1
fact(2) = 2 * fact(1) = 2 * 1 = 2
fact(3) = 3 * fact(2) = 3 * 2 = 6

We have reached the desired answer using a recursive algorithm. In JavaScript this is:

function fact(num) {
  if (num == 0)
return 1
  /* else */
return num * fact(num – 1)
}

You can call the function in the following way:

var fiveFactorial = fact(5) // 120

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us