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

Take a look at the script. number1 and number2 are initialized to 1, because f1 = 1 and f2=1. The for statement prints the numbers in the Fibonacci sequence. The initial expression of the loop is var counter = 1, which declares the loop counter and initializes its value to 1. The condition counter <= 10 means that the loop executes while the value of counter is less than or equal to 10. Note that the condition is evaluated only at the end of the loop. Incrementing the value of the loop counter is the action in this example, and is typical for for loops. In short, this loop’s attributes cause it to execute exactly ten times. The net effect is that it computes and prints the first ten numbers of the Fibonacci sequence.

Understanding the content of the loop is just plain math. After the current number is printed number2 is assigned the sum of its two succeeding numbers in the sequence. number1 should hold the value of number2 before the assignment statement. The following explains how this is done (number2' is the value of number2 before the assignment statement):

number1 = number2 – number1 == (number2' + number1) – number1 == number2'

Although you do not need to associate a command block with a loop if its body consists of only one statement, it is a common practice in this book.

The counter variable is a regular variable. Its value can change during the execution of the loop.

You can create infinite executing loops with the for statement. The break statement, which is discussed later, makes such loops meaningful by providing a way to terminate its execution. The basic structure of an infinite loop is:

for (;;)
  statement

You can also create nested for loops. The following loop prints a rectangle of asterisks (25 x 10):

for (var i = 1; i <= 10; i++) {
  for (var j = 1; j <= 25; j++) {
 document.write("*")
  }
  document.write("<BR>")
}

As you can see, the variables in the preceding example do not have meaningful names. It is common to use such identifiers as loop counters, and most experienced programmers actually do so. Unless the loop counter has a special meaning, name the variable i, j, k, etc.

while Statement

while (condition)
  statement

The while loop continues to loop while the condition (condition) is true. As opposed to the for loop, the loop is not executed at all if the condition is false at the beginning. That is, the condition is evaluated before each iteration. statement can also be a command block, allowing multiple statements.

The following loop calculates n! (n factorial):

var n = parseInt(prompt("Enter a number:", 10))
var nFactorial = 1 // will contain the value of n!
var factor = 1 // the current term by which we must multiply

while (factor <= n) {
  factor++
  nFactorial *= factor
}

alert(n + "! is " + nFactorial)

This script asks the user to enter a number. For this example, we assume the user enters a valid number (an integer between 1 and 12). nFactorial always holds the product of integers from 1 (or 2) to factor. Therefore, the loop is terminated after nFactorial is multiplied by factor, when factor is equal to the original number.

It is possible to create nested while loops. For example, you could change the script that printed a rectangle of asterisks so it uses while loops instead of for loops. You would need to initialize the counter variables before the loop statements, and increment it in the loops’ bodies.

You can also use a while statement to create an infinite loop in the following fashion:

while (1)
  statement

or

while (true)
  statement


Tip:  Unlike most C++ compilers, JavaScript’s interpreter does not insist that you use braces even when there is one statement. However, this makes the code more readable so it is a good practice to use them.


Although JavaScript does not feature an until loop, it is very simple to create one with a while statement:

  while (!condition)
statement

for…in Statement

for (variable in object)
 statement

So far we have dealt with general loops, typical to all programming languages. The for…in loop is quite different. It loops through the existing properties of a given object. It repeats a variable over all of the object’s properties.

variable is the variable that you repeat over the properties. With each pass through the loop, variable is set to the current property. object is the object to which the statement refers. The looping variable is only set to properties of the specified object. Sounds a bit complicated? Take a look at the following script segment:

var result = "" // initialize output string

for (curProperty in document) {
 result += "document." + curProperty + "<BR>"
}

document.write(result)

The script prints the properties belonging to the document object:

document.length
document.elements
document.forms
document.links
.
.
.

The order in which they are printed depends on the way they are internally stored.

The following function accepts an object and its name. It then iterates over the object’s properties and returns an HTML-ready string that lists the property names and their values.

function getProps(obj, objName) {
 var result = "" // initialize output string

 for (var i in obj) {
   result += objName + "." + i + " = " + obj[i] + "<BR>"
 }
 result += "<HR>" // add horizontal rule to output string
 return(result) // return output string
}

The problem with this function is that it cannot print the properties of a nested object. The remedy for this problem—a recursive function—is presented in Chapter 12, Building and Extending Objects.

This function is a very helpful tool, specifically for debugging scripts dealing with objects. The following statement shows how to invoke the getProps() function to list the properties of the built-in Math object.

document.write(getProps(Math, "Math"))

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us