-
Notifications
You must be signed in to change notification settings - Fork 35
Statements
syntax:
if (boolean-expression) [expression-statement | block]
[else expression-statement | block]
e.g.:
if (user_name == 'guest') quit();
or
if (user_name == 'admin') {
var user = new User();
user.role = 'admin';
}
Since the expression-statement in else could contains it...else self, so a if...else statement could be repeatedly used:
if (user_role == 'guest') {
...
} else if (user_role == 'admin') {
...
}
But an ambiguous statement as below is not recommended:
if (a < 5)
return 20;
else
if (b == 10) // not good sample
return 30;
else
return 40;
Always use block instead of expression-statement is strongly recommended:
if (a < 5) {
return 20;
} else {
if (b == 10) { // good sample
return 30;
} else {
return 40;
}
}
for statement be used to loop until condition is met. (boolean-expression to be true)
syntax:
for ( [local-]variable-declaration-list?; boolean-expression?; expression-statement-list? )
[expression-statement | block]
e.g.:
var total = 0;
for (var i = 0; i < 10; i++) {
total += i;
}
console.log(total);
The result is:
45
One or more variables or expression-statements could be used in for statement:
for (var a = 0, b = 1; a < 10 && b < 10; a++, b++) {
c = a + b;
for...in used to iterate over an object which must be enumerable. (supported by implements IEnumerable in .Net)
By default the following built-in types in ReoScript could be enumerable:
- Array
- Object
- String
syntax:
for ( [var]? identifier in expression ) [expression-statement | block]
var arr = [1,5,'ok',false];
for (element in arr) {
console.log(element);
}
The result is:
1
5
ok
false
var obj = {name: 'apple', color: 'red', amount: 5};
for (key in obj) {
console.log(key + ': ' + obj[key]);
}
The result is:
name: apple
color: red
amount: 5
var str = 'abc';
for (char in str) {
console.log(char);
}
The result is:
a
b
c
syntax:
while (boolean-expression) [expression-statement | block]
e.g.:
var i = 0;
while (i < 10) i++;
or
while (true) {
console.log('forever');
}
The following statements is terminal statement:
break; // stop and jump out current loop
continue; // stop but continue current loop from next begin
return expresion?; // stop and return from current function
syntax:
switch (expression) {
[ case expression:
| default:
| expression-statement
| block ]*
}
e.g.:
var user = get_login_user();
switch (user.role) {
case 'user':
console.log('Welcome ' + user.name + '!');
break;
case 'admin':
console.log(get_event_count() + ' event(s).');
break;
case 'guest':
forward('/common/need_login');
break;
default:
console.log('unknown role, system exit.');
exit();
break;
}
Code will be continue if no 'break' indicated:
var user = get_login_user();
switch (user.role) {
case 'user':
user.remark = 'user';
case 'admin':
user.login_time = new Date();
case 'guest':
console.log('welcome!');
break;
default:
console.log('unknown role, system exit.');
exit();
break;
}
See Error handling.