第四章 表达式
1、The if statement
if (condition) statement1 else statement2
The condition can be any expression条件可为任意一表达式,js会计算出结果,若为true则statement1...
if (condition1) statement1 else if (condition2) statement2 else statement3
2、Iterative statements迭代
do {
statement
} while (expression);
while(expression) statement
for (initialization; expression; post-loop-expression) statement
for (var i=0; i < iCount; i++){
alert(i);
}
for-in
The for-in statement is a strict iterative statement. It is used to enumerate the properties of an object.
Syntax:
for (property in expression) statement
For example:
for (sProp in window) {
alert(sProp);
}
Labeled statements
It is possible to label statements for later use with the following syntax:
label: statement
For example:
start: var iCount = 10;
The break and continue statements
Both the break and continue statements can be used in conjunction with labeled statements to return
to a particular location in the code. This is typically used when there are loops inside of loops, as in the
following example:
var iNum = 0;
outermost:
for (var i=0; i < 10; i++) {
for (var j=0; j < 10; j++) {
if (i == 5 && j == 5) {
break outermost;
}
iNum++;
}
}
alert(iNum); //outputs “55”
The with statement
The with statement is used to set the scope of the code within a particular object. Its syntax is the following:
with (expression) statement;
For example:
var sMessage = “hello world”;
with(sMessage) {
alert(toUpperCase()); //outputs “HELLO WORLD”
}
The switch statement
switch (expression) {
case value: statement
break;
case value: statement
break;
case value: statement
break;
...
case value: statement
break;
default: statement
}
Two big differences exist between the switch statement in ECMAScript and Java
In ECMAScript, the switch statement can be used on strings, and it can indicate case by nonconstant values:
在java中switch(expression)其中expression必须是int类型或能够转化为int类型的如char,bit,short int等,显然不能是字符串,而在js中是可以的,在c中也是可以的。
var BLUE = “blue”, RED = “red”, GREEN = “green”;
switch (sColor) {
case BLUE: alert(“Blue”);
break;
case RED: alert(“Red”);
break;
case GREEN: alert(“Green”);
break;
default: alert(“Other”);
}