03.JavaScript中的七种Statements

By that analogy, statements are JavaScript sentences or commands.JavaScript has a number of statements or control structures that do just this:

Conditionals(条件)

Statements like if and switch that make the JavaScript interpreter execute or skip other statements depending on the value of an expression

Loops(循环)

Statements like while and for that execute other statements repetitively

Jumps(跳转)

Statements like break, return, and throw that cause the interpreter to jump to another part of the program

1 Expression Statements 表达式语句

The simplest kinds of statements in JavaScript are expressions that have side effects.

greeting = "Hello " + name;
i *= 3;
counter++;
delete o.x;
console.log(debugMessage);
displaySpinner(); // A hypothetical function to display a spinner in a web app.
Math.cos(x);
cx = Math.cos(x);

2 Compound and Empty Statements 复杂表达式与空表达式

Just as the comma operator (§4.13.7) combines multiple expressions into a single expression, a statement block combines multiple statements into a single compound statement.

// Initialize an array a
for(let i = 0; i < a.length; a[i++] = 0) ;

if ((a === 0) || (b === 0));  // Oops! This line does nothing...
    o = null;                 // and this line is always executed.

for(let i = 0; i < a.length; a[i++] = 0) /* empty */ ;

3 Conditionals 条件

1.if statements

if (expression)
    statement

if (username == null)       // If username is null or undefined,
    username = "John Doe";  // define it

// If username is null, undefined, false, 0, "", or NaN, give it a new value
if (!username) username = "John Doe";

if (!address) {
    address = "";
    message = "Please specify a mailing address.";
}
//此处的关键点是 single-predicate是允许的

The rule in JavaScript (as in most programming languages) is that by default an else clause is part of the nearest if statement.

i = j = 1;
k = 2;
if (i === j)
    if (j === k)
        console.log("i equals k");
else
    console.log("i doesn't equal j");    // WRONG!!
//实际的执行则为
if (i === j) {
    if (j === k)
        console.log("i equals k");
    else
        console.log("i doesn't equal j");    // OOPS!
}

2.else if

if (n === 1) {
    // Execute code block #1
} else if (n === 2) {
    // Execute code block #2
} else if (n === 3) {
    // Execute code block #3
} else {
    // If all else fails, execute block #4
}

3.Switch

This is not the best solution, however, when all of the branches depend on the value of the same expression. In this case, it is wasteful to repeatedly evaluate that expression in multiple if statements.

switch(n) {
case 1:                        // Start here if n === 1
    // Execute code block #1.
    break;                     // Stop here
case 2:                        // Start here if n === 2
    // Execute code block #2.
    break;                     // Stop here
case 3:                        // Start here if n === 3
    // Execute code block #3.
    break;                     // Stop here
default:                       // If all else fails...
    // Execute code block #4.
    break;                     // Stop here
}

a more realistic example:

function convert(x) {
    switch(typeof x) {
    case "number":            // Convert the number to a hexadecimal integer
        return x.toString(16);
    case "string":            // Return the string enclosed in quotes
        return '"' + x + '"';
    default:                  // Convert any other type in the usual way
        return String(x);
    }
}function convert(x) {
    switch(typeof x) {
    case "number":            // Convert the number to a hexadecimal integer
        return x.toString(16);
    case "string":            // Return the string enclosed in quotes
        return '"' + x + '"';
    default:                  // Convert any other type in the usual way
        return String(x);
    }
}

Note that in the examples shown, the default: label appears at the end of the switch body, following all the case labels. This is a logical and common place for it, but it can actually appear anywhere within the body of the statement.

4 Loops 循环

JavaScript has five looping statements: while, do/while, for, for/of (and its for/await variant), and for/in.

1.While

let count = 0;
while(count < 10) {
    console.log(count);
    count++;
}

2 do/while

function printArray(a) {
    let len = a.length, i = 0;
    if (len === 0) {
        console.log("Empty Array");
    } else {
        do {
            console.log(a[i]);
        } while(++i < len);
    }
}

3 for

for(initialize ; test ; increment)
    statement

initialize;
while(test) {
    statement
    increment;
}

let i, j, sum = 0;
for(i = 0, j = 10 ; i < 10 ; i++, j--) {
    sum += i * j;
}

function tail(o) {                          // Return the tail of linked list o
    for(; o.next; o = o.next) /* empty */ ; // Traverse while o.next is truthy
    return o;
}

4 for/of

let data = [1, 2, 3, 4, 5, 6, 7, 8, 9], sum = 0;
for(let element of data) {
    sum += element;
}
sum       // => 45

let o = { x: 1, y: 2, z: 3 };
let keys = "";
for(let k of Object.keys(o)) {
    keys += k;
}
keys  // => "xyz"

let sum = 0;
for(let v of Object.values(o)) {
    sum += v;
}
sum // => 6

let pairs = "";
for(let [k, v] of Object.entries(o)) {
    pairs += k + v;
}
pairs  // => "x1y2z3"

let frequency = {};
for(let letter of "mississippi") {
    if (frequency[letter]) {
        frequency[letter]++;
    } else {
        frequency[letter] = 1;
    }
}
frequency   // => {m: 1, i: 4, s: 4, p: 2}

let text = "Na na na na na na na na Batman!";
let wordSet = new Set(text.split(" "));
let unique = [];
for(let word of wordSet) {
    unique.push(word);
}
unique // => ["Na", "na", "Batman!"]5 for/in

5 for/in

> Object.entries(o)
[ [ 'x', 1 ], [ 'y', 2 ], [ 'z', 3 ] ]
> for (let p in o) {
... console.log(o[p]);
... }
1
2
3
undefined
> for (let p of o) {
... console.log(o.p);
... }
Thrown:
TypeError: o is not iterable

for/in 是被淘汰的语法

5 Jumps 跳转

1 Labeled Statements

mainloop: while(token !== null) {
    // Code omitted...
    continue mainloop;  // Jump to the next iteration of the named loop
    // More code omitted...
}

2 break

// break
for(let i = 0; i < a.length; i++) {
    if (a[i] === target) break;
}

// break label 
let matrix = getData();  // Get a 2D array of numbers from somewhere
// Now sum all the numbers in the matrix.
let sum = 0, success = false;
// Start with a labeled statement that we can break out of if errors occur
computeSum: if (matrix) {
    for(let x = 0; x < matrix.length; x++) {
        let row = matrix[x];
        if (!row) break computeSum;
        for(let y = 0; y < row.length; y++) {
            let cell = row[y];
            if (isNaN(cell)) break computeSum;
            sum += cell;
        }
    }
    success = true;
}
// The break statements jump here. If we arrive here with success == false
// then there was something wrong with the matrix we were given.
// Otherwise, sum contains the sum of all cells of the matrix.

3 Continue

// Continue 
for(let i = 0; i < data.length; i++) {
    if (!data[i]) continue;  // Can't proceed with undefined data
    total += data[i];
}

4 return

function square(x) { return x*x; } // A function that has a return statement
square(2)                          // => 4

5 yield

// A generator function that yields a range of integers
function* range(from, to) {
    for(let i = from; i <= to; i++) {
        yield i;
    }
}

6 throw

function factorial(x) {
    // If the input argument is invalid, throw an exception!
    if (x < 0) throw new Error("x must not be negative");
    // Otherwise, compute a value and return normally
    let f;
    for(f = 1; x > 1; f *= x, x--) /* empty */ ;
    return f;
}
factorial(4)   // => 24

7 try/catch/finally

try {
    // Ask the user to enter a number
    let n = Number(prompt("Please enter a positive integer", ""));
    // Compute the factorial of the number, assuming the input is valid
    let f = factorial(n);
    // Display the result
    alert(n + "! = " + f);
}
catch(ex) {     // If the user's input was not valid, we end up here
    alert(ex);  // Tell the user what the error is
}

6 Miscellaneous Statements 杂项

1 with

with (object)
    statement

The with statement is forbidden in strict mode

2 debugger

function f(o) {
  if (o === undefined) debugger;  // Temporary line for debugging purposes
  ...                             // The rest of the function goes here.
}

3 “use strict”

记住便好喽。


7 Declarations 声明

The keywords const, let, var, function, class, import, and export are not technically statements, but they look a lot like statements, and this book refers informally to them as statements, so they deserve a mention in this chapter.

1 const, let, and var

2 function

3 class

4 import and export

展开阅读全文

页面更新:2024-03-14

标签:杂项   表达式   语句   语法   声明   条件   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top