Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

label

概述

标记语句(labeled statement)可以和 breakcontinue 语句一起使用。标记就是在一条语句前面加个可以引用的标识符(identifier)。

语法

label :
   statement
label
任何不是保留关键字的 JavaScript 标识符。
statement
语句。break 可用于任何标记语句(labeled statment),而 continue 可用于循环标记语句(looping labeled statements)。

描述

可使用一个标签来唯一标记一个循环,然后使用 break 或 continue 语句来指示程序是否中断循环或继续执行。

需要注意的是 JavaScript 没有 goto 语句,标记(labels)只能和 break 或 continue 一起使用。

避免使用 labels

标记(Labels)在 JavaScript 中并不经常被使用,这是因为它们会使程序变得更难于阅读和理解。应该尽可能地避免使用,根据情况,选择调用函数 或 抛出异常

示例

for 循环中使用 labeled continue

var i, j;

loop1:
for (i = 0; i < 3; i++) {      //The first for statement is labeled "loop1"
   loop2:
   for (j = 0; j < 3; j++) {   //The second for statement is labeled "loop2"
      if (i == 1 && j == 1) {
         continue loop1;
      }
      console.log("i = " + i + ", j = " + j);
   }
}

// Output is:
//   "i = 0, j = 0"
//   "i = 0, j = 1"
//   "i = 0, j = 2"
//   "i = 1, j = 0"
//   "i = 2, j = 0"
//   "i = 2, j = 1"
//   "i = 2, j = 2"
// Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2"

使用 labeled continue 语句

给定一组数据和一组测试,下面的例子统计通过测试的数据。

var itemsPassed = 0;
var i, j;

top:
for (i = 0; i < items.length; i++){
  for (j = 0; j < tests.length; j++){
    if (!tests[j].pass(items[i])){
      continue top;
    }
  }

  itemsPassed++;
}

for 循环中使用 labeled break

var i, j;

loop1:
for (i = 0; i < 3; i++) {      //The first for statement is labeled "loop1"
   loop2:
   for (j = 0; j < 3; j++) {   //The second for statement is labeled "loop2"
      if (i == 1 && j == 1) {
         break loop1;
      }
      console.log("i = " + i + ", j = " + j);
   }
}

// Output is:
//   "i = 0, j = 0"
//   "i = 0, j = 1"
//   "i = 0, j = 2"
//   "i = 1, j = 0"
// Notice the difference with the previous continue example

使用 labeled break 语句

给定一组数据和一组测试,下面的例子判断是否所有的数据均通过了测试。

var allPass = true;
var i, j;

top:
for (i = 0; items.length; i++)
  for (j = 0; j < tests.length; i++)
    if (!tests[j].pass(items[i])){
      allPass = false;
      break top;
    }

规范

Specification Status Comment
ECMAScript 3rd Edition Standard Initial definition. Implemented in JavaScript 1.2
ECMAScript 5.1 (ECMA-262)
Labelled statement
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
Labelled statement
Standard  

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

相关链接

文档标签和贡献者

 此页面的贡献者: delkaka, AlexChao
 最后编辑者: delkaka,