AJAX - The Complete Reference

(avery) #1

578 Part IV: Appendixes


The following shows a simple example of the use of these statements.

var matchi=3;
var matchj=5;
loopi:
for (var i=0;i<10;i++)
{
if (i != matchi)
continue loopi;

for (var j=0;j<10;j++)
{
if (j==matchj)
break loopi;
}
}

Object Iteration


JavaScript also supports a modification of the for loop (for/in), which is useful for
enumerating the properties of an object:

for ( [ var ] variable in objectExpression ) statement(s)

This simple example here shows for/in being used to print out the properties of
a browser’s window.navigator object:

for (var aProp in window.navigator)
document.write(aProp + "<br />");

JavaScript 1.7’s Generators and Iterators


JavaScript 1.7 also introduces a variety of interesting features, many of which are adapted
from Python features. For example, a generator is a function that does not return a value but
instead returns a yield. When you set the function, it does not execute, but instead binds the
values and sets up an iterator. You can then iteratively loop through the function and each
loop will return the next yield. As you can see from this example, it will hold the state of the
function after each call.

function showYield()
{
var call=1;
yield call;
call++;
yield call;
call++;
yield call;
}
var myGenerator = showYield();
for (var i in myGenerator)
alert(i);

//alerts 1 2 3
Free download pdf