Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

WeChat small program statement


May 18, 2021 WeChat Mini Program Development Document


Table of contents


The if statement

In WXS, you can use if statements in the following format:

  • if (expression) statement: When expression is true, the statement is executed.
  • if (expression) statement1 else statement2: When expression is true, statement1 is executed. Otherwise, statement2 is executed
  • if ... e lse if ... Else statementN allows you to select one of the executions between statement1 and statementN.

Example syntax:

// if ...

if (表达式) 语句;

if (表达式) 
  语句;

if (表达式) {
  代码块;
}


// if ... else 

if (表达式) 语句;
else 语句;

if (表达式) 
  语句;
else 
  语句;

if (表达式) {
  代码块;
} else {
  代码块;
}

// if ... else if ... else ...

if (表达式) {
  代码块;
} else if (表达式) {
  代码块;
} else if (表达式) {
  代码块;
} else {
  代码块;
}

Switch statement

Example syntax:

switch (表达式) {
  case 变量:
    语句;
  case 数字:
    语句;
    break;
  case 字符串:
    语句;
  default:
    语句;
}
  • The default branch can be omitted from writing.
  • Case keywords can only be used after: variables, numbers, strings.

Example code:

var exp = 10;

switch ( exp ) {
case "10":
  console.log("string 10");
  break;
case 10:
  console.log("number 10");
  break;
case exp:
  console.log("var exp");
  break;
default:
  console.log("default");
}

Output:

number 10

The for statement

Example syntax:

for (语句; 语句; 语句)
  语句;

for (语句; 语句; 语句) {
  代码块;
}
  • Supports the use of break, continue keywords.

Example code:

for (var i = 0; i < 3; ++i) {
  console.log(i);
  if( i >= 1) break;
}

Output:

0
1

While statement

Example syntax:

while (表达式)
  语句;

while (表达式){
  代码块;
}

do {
  代码块;
} while (表达式)
  • When the expression is true, the loop executes a statement or block of code.
  • Supports the use of break, continue keywords.