一棵树

路漫漫其修远兮 吾将上下而求索。

导航

火狐关于javascript的讲解

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/JavaScript_Overview

第一章 概述

什么是 JavaScript?

JavaScript 是一种跨平台,面向对象的脚本语言。作为一种小巧且轻量级的语言,JavaScript 无意于独立运行,而是被设计为可以轻易嵌入到其它的产品和应用中,比如 Web 浏览器。在宿主环境中,JavaScript 可以被连接到环境中的对象之上,以提供对其的编程控制。

核心的 JavaScript 中包含有一组核心的对象,包括 Array,Date 和 Math,以及一组核心的语言要素,包括操作符,控制结构和语句。出于多种目的,可以通过为其增补附加的对象,对核心 JavaScript 加以扩展;例如:

  • 客户端 JavaScript 提供了用于控制浏览器(Navigator 或者其它浏览器)以及其中的文档对象模型(DOM)的对象,从而扩展了核心 JavaScript。例如,客户端扩展允许应用程序在 HTML 的表单中加入元素,以便响应用户事件,比如鼠标点击,表单输入和页面导航。
  • 服务器端 JavaScript 提供了服务于在服务器上运行 JavaScript 的对象,从而扩展了核心 JavaScript。例如,服务器端扩展可以允许应用程序访问关系型数据库,在应用程序的不同调用间提供信息的连续性,甚至于处理服务器之上的文件。

借由 JavaScript 的 LiveConnect 功能,您可以让 Java 和 JavaScript 间实现通讯。从 JavaScript 中,您可以创建 Java 对象并访问它们的公共方法和域。从 Java 中,也可以访问 JavaScript 的对象,属性和方法。

第二章:值,变量,以及语式量

值,变量,以及语式量

在本文章中

    1. 数据类型的转换
    2. 字符串转换为数字
      1. parseInt()parseFloat()
      2. 单目加法运算符
  1. 变量
    1. 声明变量
    2. 对变量求值
    3. 变量的域
    4. 全局变量
  2. 常量
  3. 字面值(literals)
    1. 数组字面值
      1. 数组字面值中的多余逗号
    2. 布尔字面值
    3. 整数
    4. 浮点数字面值
    5. 对象字面值
    6. 字符串字面值
      1. 在字符串中使用的特殊字符
      2. 转义字符
  4. Unicode编码
    1. 兼容于ASCII和ISO标准的Unicode编码
    2. Unicode转义序列
    3. JavaScript文件中的Unicode字符
    4. 用Unicode编码显示字符
  5. 参考资料
(译注:标题中的literals可译为字面量/值,术语量/值,语式量/值)

本章讨论在JavaScript语言中,用以识别和描述JavaScript表达式基本构件的一些值:变量,常量和字面值。(译者:第一句话就好难译通顺,道非常之不可道,接近JS的本质了?)

JavaScript语言可以识别下面 5 种不同类型的值:

 

类型

类型值范例 / 注释

Numbers

42, 3.14159

Logical (Boolean)

true / false

Strings

"Howdy"

null

一个特殊的用于表示空值的关键字;同时null也是一个原始(primitive)值。JavaScript语言是区分大小写的,所以null不同于NullNULL或者任何其他变体

undefined

一个值未定义的顶层属性;undefined 同时也是原始值。

仅凭这些为数不多的数据类型,你的应用程序就能够执行有用的功能。

Objects和 functions 是本语言的其他两个基本要素。你可以将对象视为存放值的命名容器,而将函数视为你的应用程序能够执行的过程(procedures)。

数据类型的转换

JavaScript是一种支持动态数据类型的语言。这意味着你定义变量时不必指定数据类型,而数据类型会在脚本执行需要时自动转换。那么,你可以这样来定义变量:

var answer = 42;

然后,你还可以给同一个变量分配一个字符串值,例如:

answer = "Thanks for all the fish...";

因为 JavaScript 是动态类型的,这样的分配并不会提示出错。

在包含加法运算符的数字和字符串表达式中,JavaScript 会把数字值转换为字符串。例如,假设有如下的语句:

x = "The answer is " + 42 // "The answer is 42"
y = 42 + " is the answer" // "42 is the answer"

在包含其它运算符(译注:如下面的“-”)时,JavaScript语言不会把数字变为字符。例如(译注:第一例是数学运算,第二例仍是字符串运算):

"37" - 7 // 30
"37" + 7 // "377"

字符串转换为数字

有一些方法可以将内存中表示一个数字的字符串转换为对应的数字

parseInt()parseFloat()

参见:parseInt()parseFloat()的相关页面。

parseInt 仅能够返回全部的数字,所以使用它会丢失小数部分。另外,调用 parseInt 时最好总是带上进制(radix) 参数,这个参数用于指定使用哪一种数制。

单目加法运算符

将字符串转换为数字的另一种方法是使用单目加法运算符。

"1.1" + "1.1" = "1.11.1"
(+"1.1") + (+"1.1") = 2.2   // Note: the parentheses are added for clarity, not required.

变量

在应用程序中,你使用变量来为值命名。变量的名称,或称为标识符,需要遵守一定的规则。

在JavaScript语言中,一个标识符必须以字母、下划线(_)或者美元($)符号开头;后续的字符可以包含数字(0-9)。因为JavaScript语言是区分大小写的,这里所指的字母可以是(大写的)“A”到字母“Z”和(小写的)“a”到“z”。

从JavaScript 1.5版开始,你可以使用 ISO 8859-1 或 Unicode 编码的字符作标识符,例如å和ü。你也可以使用\uXXXX字样的转义序列 Unicode escape sequences作标识符。

合法的标识符示例:Number_hits,temp99 和 _name

声明变量

你可以用以下两种方式声明变量:

  • 使用关键词 var。例如,var x = 42。这个语法可以同时用来声明局部和全局变量。
  • 直接赋值。例如,x = 42。这样就声明了一个全局变量并会导致JavaScript编译时产生一个严格警告。因而你应避免使用这种非常规格式。

对变量求值

用var声明时未赋初值的变量,值会被设定为undefined(译注:即未定义值,本身也是一个值)

试图访问一个未初始化的变量会导致一个ReferenceError异常被抛出:

var a;
console.log("The value of a is " + a); // logs "The value of a is undefined"
console.log("The value of b is " + b); // throws ReferenceError exception

你可以使用undefined来确定变量是否已赋值。以下的代码中,变量input未被赋值,因而if条件语句的求值结果是true

var input;
if(input === undefined){
  doThis();
} else {
  doThat();
}

undefined值在布尔类型环境中会被当作false。例如,下面的代码将运行函数myFunction,因为数组myArray中的元素未被赋值:

var myArray = new Array();
if (!myArray[0]) myFunction();

数值类型环境中undefined值会被转换为NaN(译注:NaN为“不是一个数字”的缩写)。

var a;
a + 2 = NaN

当你对一个空变量求值时,空值null在数值类型环境中会被当作0来对待,而布尔类型环境中会被当作false
。例如:

var n = null;
console.log(n * 32); // logs 0

变量的域

在所有函数之外声明的变量,叫做全局变量,因为它可被当前文档中的其他代码所访问。在函数内部声明的变量,叫做局部变量,因为它只能在该函数内部访问。

JavaScript没有 语句块 作用域;相反,语句块中声明的变量将成为语句块所在代码段的局部变量。例如,如下的代码将在控制台输出 5,因为 x 的作用域是声明了 x 的那个函数(或全局范围),而不是 if 语句块。

if (true) {
  var x = 5;
}
console.log(x); //在函数中声明的变量为局部变量

JavaScript 变量的另一特别之处在于,你可以引用稍后声明的变量,而不会引发异常。这一概念称为变量声明提升(hoisting);JavaScript 变量感觉上是被“举起”或提升到了所有函数和语句之前。但是,未被初始化的变量仍将返回 undefined 值

/**
 * Example 1
 */
console.log(x === undefined); // logs "true"
var x = 3;
/**
 * Example 2
 */
// will return a value of undefined
var myvar = "my value";
 (function() {
  console.log(myvar); // undefined
  var myvar = "local value";
})();

上面的例子2,也可写作:

var myvar = "my value";
 (function() {
  var myvar;
  console.log(myvar); // undefined  这个就是对上个例子的解析
  myvar = "local value";
})();

由于存在变量声明提升,一个函数中所有的var语句应尽可能地放在接近函数顶部的地方。这大大地提升了程序代码的清晰度。

全局变量

全局变量实际上是全局对象的属性。在网页中,(译注:缺省的)全局对象是 window,所以你可以用形如window.variable的语法来设置和访问全局变量。

因此,你可以通过指定 window 或 frame 的名字,从一个 window 或 frame 访问另一个 window 或 frame 中声明的变量。例如,设想一个叫 phoneNumber 的变量在文档FRAMESET里被声明,你可以在子框架里用 parent.phoneNumber 来引用它。

常量

你可以用关键字 const 创建一个只读的常量。常量标识符的命名规则和变量的相同:必须以字母、下划线或美元符号开头并可以包含有字母、数字或下划线。

const prefix = '212';

常量不可以通过赋值改变其值,也不可以在脚本运行时重新声明。

常量,包括全局常量,都必须带const关键字,除此之外,常量的作用域规则与变量相同。若const关键字被省略了,该标识符将被视为变量。

在同一作用域中,不能用与变量或函数同样的名字来命名常量。例如:

// THIS WILL CAUSE AN ERROR
function f() {};
const f = 5;
 // THIS WILL CAUSE AN ERROR ALSO
function f() {

const g = 5;
  var g;
//statements
}

字面值(literals)

(译注:字面值是由语法表达式定义的常量;或,通过由一定字辞组成的语词表达式定义的常量)

在JavaScript中,你可以使用各种字面值。这些字面值是脚本中按字面意思给出的固定的值,而不是变量。(译注:字面值是常量,其值是固定的,而且在程序脚本运行中不可更改,比如false,3.1415,thisIsStringOfHelloworld ,invokedFunction: myFunction("myArgument")。本节将介绍以下类型的字面值:

数组字面值

数组字面值是一个封闭在方括号对([])中的包含有零个或多个表达式的列表,其中每个表达式代表数组的一个元素。当你使用数组字面值创建一个数组时,该数组将会以指定的值作为它的元素进行初始化,而其长度被设定为元素的个数。

下面的示例用3个元素生成数组coffees,它的长度是3。

var coffees = ["French Roast", "Colombian", "Kona"];

注意 这里的数组字面值也是一种对象初始化器。参考对象初始化器的使用

若在顶层脚本里用字面值创建数组,JavaScript语言会在每次对包含该数组字面值的表达式求值时解释该数组。另一方面,在函数中使用的数组,将在每次调用函数时被创建一次。

数组字面值同时也是数组对象。有关数组对象的详情请参见数组对象一文。

数组字面值中的多余逗号

(译注:声明时)你不必列举数组字面值中的所有元素。若你在同一行中连写两个逗号(,),数组中就会产生一个没被指定的元素,其初始值是undefined。以下示例创建了一个名为fish的数组:

var fish = ["Lion", , "Angel"];

这个数组中,有两个已被赋值的元素,和一个空元素(fish[0]是"Lion",fish[1]undefined,而fish[2]是"Angel";译注:此时数组的长度属性fish.length是3)。

若你在元素列表的尾部添加了一个逗号(,),它会被忽略。在下面的例子中,该数组的长度是3。并不存在myList[3]这个元素(译注:这是指数组的第4个元素噢,作者是在帮大家复习数组元素的排序命名方法)。元素列表中所有其它的逗号都表示一个新元素(的开始)。(注意:尾部的逗号在早期版本的浏览器中会产生错误,因而编程时的最佳实践就是移除它们。译注:而“现代”的浏览器似乎鼓励这种方式,因为好多网页中都这么写

var myList = ['home', , 'school', ];

在下面的例子中,数组的长度是4,元素myList[0]myList[2]缺失(译注:没被赋值,因而是undefined)。

var myList = [ , 'home', , 'school'];

又一个例子,在这里该数组的长度是4,元素myList[1]myList[3]被漏掉了。(但是)只有最后的那个逗号被忽略。

var myList = ['home', , 'school', , ];

理解多余的逗号(在脚本运行时会被如何处理)的含义,对于从语言层面理解JavaScript是十分重要的。但是,你自己写代码时:显式地讲缺失的元素声明为undefined,将大大增加你的代码的清晰度和可维护性。(译注:此段话的重要性甚至超过整篇文章。译者:还有为啥不举例说明呢?)

布尔字面值

(译注:即逻辑字面值)

布尔类型有两种字面值:truefalse

不要混淆(才怪!)作为布尔对象的真和假与布尔类型的原始值truefalse。(译者:难懂,这分明让人抓狂嘛,为啥不立刻举例说明呢?)布尔对象是原始布尔数据类型的一个包装器。参见 布尔对象

整数

(译注:原文如此,没写成“整数字面值”)

整数可以被表示成十进制(基数为10)、十六进制(基数为16)以及八进制(基数为8)。

  • 十进制整数字组成的数字序列,不带前导0(零)。
  • 带前导0(零)的整数字面值表明它是八进制。八进制整数只能包括数字0-7。
  • 前缀0x或0X表示十六进制。十六进制整数,可以包含数字(0-9)和字母a~f或A~F。

八进制整数字面值在ECMA-262,第3版标准(严格模式下 中被弃用并移除。不过JavaScript 1.5为了后向兼容仍然保留了支持。

整数字面值例子如下:

0, 117 and -345 (decimal, base 10)
015, 0001 and -077 (octal, base 8) 
0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16)

浮点数字面值

浮点数字面值可以有以下的组成部分:

  • 一个十进制整数,它可以带符号(即前面的“+”或“ - ”号),
  • 一个小数点(“.”),
  • 一个小数部分(由一串十进制数表示),
  • 一个指数部分。

指数部分是以“e”或“E”开头后面跟着一个整数,可以有正负号(即前面写“+”或“-”)。一个浮点数字面值必须至少有一位数字,后接小数点或者“e”(大写“E”也可)组成。

一些浮点数字面值的例子,如3.1415,-3.1E13,.1e12以及2E-12。

简言之,其语法是:

[digits][.digits][(E|e)[(+|-)]digits]

例如:

3.14
2345.789
.3333333333333333333

对象字面值

对象字面值是封闭在花括号对({})中的一个对象的零个或多个"属性名-值"对的(元素)列表。你不能在一条语句的开头就使用对象字面值,这将导致 错误或非你所预想的行为,因为此时左花括号({)会被认为是一个语句块的起始符号。(译者:这 里需要对语句statement、块block等基本名词的解释)

以下是一个对象字面值的例子。对象car的第一个元素(译注:即一个属性双值对)定义了属性myCar;第二个元素,属性getCar,引用了一个函数(即CarTypes("Honda"));第三个元素,属性special,使用了一个已有的变量(即Sales)。

var Sales = "Toyota";
 function CarTypes(name) {
  return (name == "Honda") ?
    name :
    "Sorry, we don't sell " + name + "." ;
}
 var car = { myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales };
 console.log(car.myCar);   // Saturn
console.log(car.getCar);  // Honda
console.log(car.special); // Toyota

更进一步的,你可以使用数字或字符串字面值作为属性的名字,或者在另一个字面值内嵌套上一个字面值。如下的示例中使用了这些可选项。

var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
 console.log(car.manyCars.b); // Jeep
console.log(car[7]); // Mazda

这里请注意:

var foo = {a: "alpha", 2: "two"};
console.log(foo.a);    // alpha
console.log(foo[2]);   // two
//console.log(foo.2);  // Error: missing ) after argument list
//console.log(foo[a]); // Error: a is not defined
console.log(foo["a"]); // alpha
console.log(foo["2"]); // two

字符串字面值

字符串字面值可以包含有零个或多个字符,由双引号(")对或单引号(‘)对包围。字符串被限定在同种引号之间;也即,必须是成对单引号或成对双引号。下面的例子都是字符串字面值:

  • "foo"
  • 'bar'
  • "1234"
  • "one line \n another line"
  • "John's cat"

你可以在字符串字面值上使用字符串对象的所有方法——JavaScript会自动将字符串字面值转换为一个临时字符串对象,调用该方法,然后废弃掉那个临时的字符串变量。你也能用对字符串字面值使用类似String.length的属性:

"John's cat".length

除非有特别需要使用字符串对象,你应当始终使用字符串字面值。要查看字符串对象的有关细节,请参见字符串对象

在字符串中使用的特殊字符

作为一般字符的扩展,你可以在字符串中使用特殊字符,如下例所示。

"one line \n another line"

以下表格列举了你能在JavaScript的字符串中使用的特殊字符。

表 2.1 JavaScript 特殊字符

Character

Meaning

\b

Backspace

\f

Form feed

\n

New line

\r

Carriage return

\t

Tab

\v

Vertical tab

\'

Apostrophe or single quote

\"

Double quote

\\

Backslash character (\).

\XXX

The character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.

\xXX

The character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.

\uXXXX

The Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode escape sequences.

转义字符

对于那些未出现在表2.1中的字符,其所带的前导反斜线'\'将被忽略。但是,这一用法已被废弃,应当避免使用。

通过在引号前加上反斜线'\',可以在字符串中插入引号,这就是引号转义。例如:

var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
console.log(quote);

代码的运行结果为:

He read "The Cremation of Sam McGee" by R.W. Service.

要在字符串中插入'\'字面值,必须转义反斜线。例如,要把文件路径 c:\temp 赋值给一个字符串,可以采用如下方式:

var home = "c:\\temp";

也可以在换行之前加上反斜线以转义换行(译注:实际上就是一条语句拆成多行书写),这样反斜线和换行都不会出现在字符串的值中。

var str = "this string \
is broken \
across multiple\
lines."
console.log(str);   // this string is broken across multiplelines.

Javascript没有“heredoc”语法,但可以用行末的换行符转义和转义的换行来近似实现 

var poem = 
"Roses are red,\n\
Violets are blue.\n\
I'm schizophrenic,\n\
And so am I."

Unicode编码

Unicode是一种通用字符编码标准,用于世界上主要书面语言的交换和显示。它涵盖美洲,欧洲,中东,非洲,印度,亚洲和环太平洋地区的语言,还包括古文字和技术符号。 Unicode允许多语言文本的交换、处理和显示,以及通用的技术和数学符号的使用。它有望解决多语言计算的国际化问题,如不同国家的文字标准,以解决国际化问题。但目前,并非所有的现代或古老的文字都得到了支持。

Unicode字符集可用于所有已知的编码。 Unicode字符集是在ASCII(美国信息交换标准码)字符集后建立的,它为每个字符设定一个数值和名称。字符编码指定字符的本体(identity)和数值(编码位置),以及这个数值的位(bit)表示。 16位的数字值(编码值)定义为一个带前缀U的十六进制数,例如,U+0041代表A。这个值的唯一名称是大写的拉丁字母A。

注意:1.3 版本之前的JavaScript并不支持Unicode编码。

兼容于ASCII和ISO标准的Unicode编码

Unicode编码完全兼容ISO 10646的子集ISO/IEC 10646-1; 1993。

若干编码标准(包括UTF-8,UTF-16和ISO UCS-2)用于将Unicode表示为实际的二进制位。

Unicode的UTF-8编码与ASCII字符是兼容,并且被许多程序所支持。前128个Unicode字符与ASCII字符一一对应,并具有相同的字节值。从U+0020至U+007E的Unicode字符等价于从0x20到0x7E的ASCII字符。ASCII支持拉丁字母并使用7位字符集,而UTF-8的每个字符占用一到四个8位组(8位组octet,即1个字节或8位),这样可以表示数百万个字符。另一种编码标准,UTF-16,使用两个字节来表示Unicode字符。转义序列允许UTF-16用4个8位组表示Unicode字符, ISO UCS-2(通用字符集)则使用两个字节。

JavaScript和Navigator支持UTF-8/Unicode,这意味着你可以在Javascript程序中使用非拉丁、国际化或本地化的字符,以及特殊的技术符号。Unicode提供了一种标准的方式来编码多语言文本。由于UTF-8的Unicode编码与ASCII兼容,程序可以使用ASCII字符。您可以在Javascript的注释、字符串字面值、标识符和正则表达式中使用非ASCII的Unicode字符。

Unicode转义序列

你可以在字符串字面值、正则表达式和标识符中使用Unicode转义序列。转义序列由6个ASCII字符构成:\u和一个4位十六进制数字。例如,\u00A9表示版权符号。每一个Unicode转义序列在JavaScript中被解释为一个字符。

下面的代码返回一个版权符号和字符串“Netscape Communications”。

var x = "\u00A9 Netscape Communications";

下表列出了常用特殊字符的Unicode值。

表 2.2 特殊字符的Unicode值

类别

Unicode

名称

格式名称

空白字符

\u0009

Tab

<TAB>

\u000B

Vertical Tab

<VT>

\u000C

Form Feed

<FF>

\u0020

Space

<SP>

换行符

\u000A

Line Feed

<LF>

\u000D

Carriage Return

<CR>

其他Unicode转义序列

\u0008

Backspace

<BS>

\u0009

Horizontal Tab

<HT>

\u0022

Double Quote

"

\u0027

Single Quote

'

\u005C

Backslash

\

JavaScript中Unicode转义序列的用法和Java不同。在JavaScript中,转义序列绝不会首先被理解为一个特殊字符。例如,在一个字符串的换行符转义序列不终止字符串,它被解释的功能。Javascript忽略注释中的任何转义序列。在Java中,如果在单行注释中使用转义序列,则它被解释为一个Unicode字符。对于一个字符串字面量,Java编译器首先解释转义序列。例如,如果在JavaScript(译注:此处原文误作Java)中使用一个行结束符转义字符(例如,\u000A),它终止字符串文字。而在Java中这样做将导致一个错误,因为(Unicode)换行符不允许出现在字符串字面值中,必须使用\n换行。在JavaScript中,转义序列的效果和\n一样。

JavaScript文件中的Unicode字符

早期的Gecko默认使用Latin-1字符作为从XUL文件加载的JavaScript代码文件的编码。在Gecko 1.8之后,则根据XUL文件的编码来推断。请参考在XUL JavaScript中使用国际字符一文内的更多信息。

用Unicode编码显示字符

你可以使用Unicode显示不同语言的字符或技术符号。为了正确显示字符,客户端,如Mozilla Firefox或Netscape,必须支持Unicode。此外,客户端必须有可用的合适的Unicode字体,而且客户端平台必须支持Unicode。通常情况下,Unicode字体无法显示所有的Unicode字符。一些平台,如Windows 95,提供了对Unicode的部分支持。

要接收非ASCII字符的输入,客户端需要将输入作为Unicode来发送。使用标准的增强型键盘,客户端无法轻易地输入Unicode支持的附加字符。有时,输入Unicode字符的唯一办法就是使用Unicode转义序列。

第三章:表达式和运算符

本章描述了JavaScript的表达式和运算符,包括赋值,比较,数值计算,位运算,逻辑运算,字符串(运算)和特殊运算符。

表达式

表达式 是一组可以计算出一个数值的有效的代码的集合

从概念上讲,有两种表达式: 它们是:把一个值赋值给一个变量和那些可以简单得到一个值的式子。比如,x=7 就是第一种。这个表达式用“=”运算符 把值7赋值给变量x。这个表达式自己的值等于7。而代码 3 + 4则是第二种表达式,这个表达式用“+”运算符把3和4相加却并没有将结果7赋值给一个变量。

JavaScript 有如下类型的表达式:

  • 算术: 求值结果为数字, 例如 3.14159. (通常使用 算术运算符.)
  • 字符串: evaluates to a character string, 例如, "Fred" or "234". (通常使用 字符串运算符.)
  • 逻辑: 求值结果为true或false. (通常包含 逻辑运算符.)
  • 对象: 求值结果为对象. (到 特殊运算符 中查阅多种不同的求值结果为对象的表达式.)

运算符

JavaScript中的运算符有以下几种。本节将介绍这些运算符和运算符的优先级 

JavaScript包含 二元运算符   和 一元运算符, 以及一个特殊的三元运算符:条件运算符。 二元运算符要求在运算符前后各有一个操作数,如下所示:

操作数1运算符 操作数2

例如, 3+4 、 x*y。

一元运算符则只需要一个操作数,操作数可以在运算符的前面或后面:

运算符 操作数

或者

操作数 运算符

例如, x++  和 ++x。

赋值运算符

赋值运算符基于它的右操作数的值来为左操作数赋值. 最基本的赋值运算符是等号 (=), 它将右操作数的值赋给左操作数。就是说, x = y 将 y 的值赋给 x.

其他的赋值运算符是下表所列出的运算的简写:

表 3.1 赋值运算符

简写运算符

含义

x += y

x = x + y

x -= y

x = x - y

x *= y

x = x * y

x /= y

x = x / y

x %= y

x = x % y

x <<= y

x = x << y

x >>= y

x = x >> y

x >>>= y

x = x >>> y

x &= y

x = x & y

x ^= y

x = x ^ y

x |= y

x = x | y

比较运算符

比较运算符比较它的操作数并基于比较值是否为真来返回一个逻辑值. 操作数可以是数字、字符串、逻辑值或者对象. 字符串的比较是基于标准字典序,使用字符的Unicode值. 大多数情况下,如果两个操作数不是同一种类型的,JavaScript会尝试将它们转换为适合比较的类型.通常,转换的最终结果是进行数值比较. 唯一的例外是===和!==, 他们执行的是严格的相等性比较而不会在进行判断之前进行操作数类型转换 . 下表基于这段示例代码详述了比较运算符:

var var1 = 3, var2 = 4;

表 3.2 比较运算符

操作数

Description

返回true的例子

相等 (==)

Returns true if the operands are equal.

3 == var1

"3" == var1

3 == '3'

不等 (!=)

Returns true if the operands are not equal.

var1 != 4
var2 != "3"

严格相等 (===)

Returns true if the operands are equal and of the same type. 另见 Object.is 和 sameness in JS.

3 === var1

严格不等 (!==)

Returns true if the operands are not equal and/or not of the same type.

var1 !== "3"
3 !== '3'

大于 (>)

Returns true if the left operand is greater than the right operand.

var2 > var1
"12" > 2

大于等于 (>=)

Returns true if the left operand is greater than or equal to the right operand.

var2 >= var1
var1 >= 3

小于 (<)

Returns true if the left operand is less than the right operand.

var1 < var2
"12" < "2"

小于等于 (<=)

Returns true if the left operand is less than or equal to the right operand.

var1 <= var2
var2 <= 5

算术运算符

算术运算符使用数值(字面量或者变量)作为操作数并返回一个数值.标准的算术运算符就是加减乘除(+-*/).当操作数是浮点数时,这些运算符表现得跟它们在大多数编程语言中一样(特殊要注意的是,除零会产生Infinity(译者注:大多数编程语言除零会抛出异常))例如:

console.log(1 / 2); /* prints 0.5 */

console.log(1 / 2 == 1.0 / 2.0); /* also this is true */

另外,JavaScript还提供了下表中的算术运算符.

表 3.3 算术运算符

Operator

Description

Example

%
(求余)

二元运算符. 返回相除之后的余数.

13 % 5 返回 3.(译者注:原文的例子是12%5得2,这个例子实在是不好,12与5求余求模都得2)

++
(自增)

一元运算符. 将操作数的值加一. 如果放在操作数前面 (++x), 则返回加一后的值; 如果放在操作数后面 (x++), 则返回操作数原值,然后再将操作数加一.

If x is 3, then ++x sets x to 4 and returns 4, whereas x++ returns 3 and, only then, sets x to 4.

--
(自减)

一元运算符. 将操作数的值减一. 前后缀两种用法的返回值类似自增运算符.

If x is 3, then --x sets x to 2 and returns 2, whereas x-- returns 3 and, only then, sets x to 2.

-
(一元负值符)

一元运算符,返回操作数的负值.

If x is 3, then -x returns -3.

位运算符

位运算符将它的操作数视为32位的二进制串(0和1组成)而非十进制八进制或十六进制数.例如:十进制数字9用二进制表示为1001,位运算符就是在这个二进制表示上执行运算,但是返回结果是标准的JavaScript数值.

下表总结了 JavaScript的位运算符.

表 3.4 位运算符

Operator

Usage

Description

二进制与 AND

a & b

Returns a one in each bit position for which the corresponding bits of both operands are ones.

二进制或 OR

a | b

Returns a one in each bit position for which the corresponding bits of either or both operands are ones.

二进制异或 XOR

a ^ b

Returns a one in each bit position for which the corresponding bits of either but not both operands are ones.

二进制非 NOT

~ a

Inverts the bits of its operand.

左移位

a << b

将a的二进制串向左移动b位,右边移入0.

Sign-propagating right shift

a >> b

Shifts a in binary representation b bits to the right, discarding bits shifted off.

Zero-fill right shift

a >>> b

Shifts a in binary representation b bits to the right, discarding bits shifted off, and shifting in zeros from the left.

位逻辑运算符

概念上来讲, 位逻辑运算符工作流程如下:

  • 操作数被转换为32位整型,以位序列(0和1组成)表示.
  • 第一个操作数的每一位都与第二个操作数的对应位组对: 第一位对应第一位,第二位对应第二位,以此类推.
  • 运算符被应用到每一对"位"上, 最终的运算结果由每一对“位”的运算结果组合起来.

例如,十进制数9的二进制表示是1001,十进制数15的二进制表示是1111.因此,当位运算符应用到这两个值时,结果如下:

表 3.5 位运算符范例

表达式

结果

二进制描述

15 & 9

9

1111 & 1001 = 1001

15 | 9

15

1111 | 1001 = 1111

15 ^ 9

6

1111 ^ 1001 = 0110

~15

-16

~00000000...00001111 = 11111111...11110000

~9

-10

~00000000...00001001 = 11111111...11110110

注意位运算符“非”将所有的32位取反,而值的最高位(最左边的一位)为1则表示负数(2-补码表示法).

移位运算符

移位运算符带两个操作数:第一个是待移位的数,第二个是指定第一个数要被移多少位的数. 移位的方向由运算符来控制.

移位运算符列表如下.

表 3.6 移位运算符

运算符

描述

范例

<<
(左移位)

将第一个操作数向左移动指定数量的位. 左边移出位被抛弃. 左边移出的几位被丢弃.右边多出的空位由0补齐

9<<2 yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.

>>
(带符号右移)

将第一个操作数向右移动指定数量的位. 右边移出位被抛弃. 左边多出的空位由原值的最左边数字补齐.

9>>2 yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, -9>>2 yields -3, because the sign is preserved.

>>>
(补零右移)

将第一个操作数向右移动指定数量的位. 右边移出位被抛弃. 左边多出的空位由0补齐.

19>>>2 yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

逻辑运算符

逻辑运算符常用于布尔(逻辑)值之间; 当操作数都是布尔值时,返回值也是布尔值。 不过实际上&&和||返回的是一个特定的操作数的值,所以当它用于非布尔值的时候,返回值就可能是非布尔值。 逻辑运算符的描述如下。

表 3.6 逻辑运算符

运算符

范例

描述

&&

expr1 && expr2

(逻辑与) 如果expr1能被转换为false,那么返回expr1;否则,返回expr2。因此,&&用于布尔值时,当操作数都为true时返回true;否则返回false.

||

expr1 || expr2

(逻辑或) 如果expr1能被转换为true,那么返回expr1;否则,返回expr2。因此,||用于布尔值时,当任何一个操作数为true则返回true;如果操作数都是false则返回false。

!

!expr

(逻辑非) 如果操作数能够转换为true则返回false;否则返回true。

能被转换为false的值有null, 0, 空字符串("")和undefined。

下面是&&(逻辑与)操作符的示例。

var a1 =  true && true;     // t && t returns true

var a2 =  true && false;    // t && f returns false

var a3 = false && true;     // f && t returns false

var a4 = false && (3 == 4); // f && f returns false

var a5 = "Cat" && "Dog";    // t && t returns Dog

var a6 = false && "Cat";    // f && t returns false

var a7 = "Cat" && false;    // t && f returns false

下面是||(逻辑或)操作符的示例。

var o1 =  true || true;     // t || t returns true

var o2 = false || true;     // f || t returns true

var o3 =  true || false;    // t || f returns true

var o4 = false || (3 == 4); // f || f returns false

var o5 = "Cat" || "Dog";    // t || t returns Cat

var o6 = false || "Cat";    // f || t returns Cat

var o7 = "Cat" || false;    // t || f returns Cat

下面是!(逻辑非)操作符的示例。

var n1 = !true;  // !t returns false

var n2 = !false; // !f returns true

var n3 = !"Cat"; // !t returns false

短路求值

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && anything is short-circuit evaluated to false.
  • true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

字符串运算符

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings. For example, "my " + "string" returns the string "my string".

The shorthand assignment operator += can also be used to concatenate strings. For example, if the variable mystring has the value "alpha", then the expression mystring += "bet" evaluates to "alphabet" and assigns this value to mystring.

特殊运算符

JavaScript有下列特殊运算符:

条件运算符

条件运算符是JavaScript中唯一需要三个操作数的运算符。运算的结果根据给定条件在两个值中取其一。语法为:

condition ? val1 : val2

如果condition为true,则结果取val1。否则为val2。你能够在任何允许使用标准运算符的地方使用条件运算符。

例如,

var status = (age >= 18) ? "adult" : "minor";

当age大于等于18的时候,语句将“adult”赋值给status;否则将“minor”赋值给status。

逗号操作符

逗号操作符(,)对两个操作数进行求值并返回第二个操作数的值。它常常用在for循环中,在每次循环时对多个变量进行更新。

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to increment two variables at once. The code prints the values of the diagonal elements in the array:

for (var i = 0, j = 9; i <= 9; i++, j--)

  document.writeln("a[" + i + "][" + j + "]= " + a[i][j]);

delete

delete 操作,删除一个对象或者一个对象的属性, 或者一个数组中某一个键值. 语法如下:

delete objectName;

delete objectName.property;

delete objectName[index];

delete property; // legal only within a with statement

objectName是一个对象名, property 是一个已经存在的属性, index是数组中的一个已经存在的键值的索引值.

第四行的形式只在一个声明的状态下是合法的, 从对象中删除一个属性。

你能使用 delete 删除各种各样的隐式声明, 但是被var声明的除外 .

如果 delete 操作成功, 属性或者元素会变成 undefined. 如果 delete可行会返回true,如果不成功返回false.

x = 42;

var y = 43;

myobj = new Number();

myobj.h = 4;    // create property h

delete x;       // returns true (can delete if declared implicitly)

delete y;       // returns false (cannot delete if declared with var)

delete Math.PI; // returns false (cannot delete predefined properties)

delete myobj.h; // returns true (can delete user-defined properties)

delete myobj;   // returns true (can delete if declared implicitly)

删除数组元素

删除数组中的元素时,数组的长度是不变的,例如delete a[3], a[4]  ,a[4] 和a[3] 仍然存在变成了undefined.

delete 删除数组中的一个元素, 这个元素就不在数组中了. 例如, trees[3]被删除,trees[3] 仍然可寻址并返回undefined.

var trees = new Array("redwood", "bay", "cedar", "oak", "maple");

delete trees[3];

if (3 in trees) {

  // this does not get executed(不会被执行)

}

如果想让数组中存在一个元素但是是undefined值,使用undefined关键字而不是delete操作. 如下: trees[3]分配一个undefined,但是这个数组元素仍然存在:

var trees = new Array("redwood", "bay", "cedar", "oak", "maple");

trees[3] = undefined;

if (3 in trees) {

  // this gets executed(会被执行)

}

in

in操作,如果指定的属性在指定的对象中会返回true,语法如下:

propNameOrNumber in objectName

wherepropNameOrNumber是一个字符串或数值表达式代表一个属性名或数组索引objectName是一个对象名.

下面的例子是 in 操作的常见用法.

// Arrays

var trees = new Array("redwood", "bay", "cedar", "oak", "maple");

0 in trees;        // returns true

3 in trees;        // returns true

6 in trees;        // returns false

"bay" in trees;    // returns false (you must specify the index number,

                   // not the value at that index)

"length" in trees; // returns true (length是数组的属性)

 

// Predefined objects

"PI" in Math;          // returns true

var myString = new String("coral");

"length" in myString;  // returns true

 

// Custom objects

var mycar = {make: "Honda", model: "Accord", year: 1998};

"make" in mycar;  // returns true

"model" in mycar; // returns true

instanceof

instanceof 操作,如果对象是某种指定类型返回ture.语法如下:

objectName instanceof objectType

objectName 是对象的名称相较于objectType,objectType是对象的类型, 例如Date或 Array.

当你需要确认一个对象在运行时的类型时使用instanceof.例如, 抓取异常, 你可以根据抛出异常的类型分类处理异常代码.

例如, 下面的代码使用instanceof去判断 theDay是否是一个 Date 对象. 因为theDay是一个Date对象, 所以if中的代码会执行.

var theDay = new Date(1995, 12, 17);

if (theDay instanceof Date) {

  // statements to execute 执行

}

new

You can use the new operator to create an instance of a user-defined object type or of one of the predefined object types Array, Boolean, Date, Function, Image, Number, Object, Option, RegExp, or String. On the server, you can also use it with DbPool, Lock, File, or SendMail. Use new as follows:

var objectName = new objectType([param1, param2, ..., paramN]);

You can also create objects using object initializers, as described in using object initializers.

See the new operator page in the Core JavaScript Reference for more information.

this

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this as follows:

this["propertyName"]

this.propertyName

Example 1.
Suppose a function called validate validates an object's value property, given the object and the high and low values:

function validate(obj, lowval, hival){

  if ((obj.value < lowval) || (obj.value > hival))

    alert("Invalid Value!");

}

You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

<B>Enter a number between 18 and 99:</B>

<INPUT TYPE="text" NAME="age" SIZE=3

   onChange="validate(this, 18, 99);">

Example 2.
When combined with the form property, this can refer to the current object's parent form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm.

<FORM NAME="myForm">

Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">

<P>

<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"

   onClick="this.form.text1.value = this.form.name;">

</FORM>

typeof

The typeof operator is used in either of the following ways:

  1. typeof operand
  2. typeof (operand)

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

Suppose you define the following variables:

var myFun = new Function("5 + 2");

var shape = "round";

var size = 1;

var today = new Date();

The typeof operator returns the following results for these variables:

typeof myFun;     // returns "function"

typeof shape;     // returns "string"

typeof size;      // returns "number"

typeof today;     // returns "object"

typeof dontExist; // returns "undefined"

For the keywords true and null, the typeof operator returns the following results:

typeof true; // returns "boolean"

typeof null; // returns "object"

For a number or string, the typeof operator returns the following results:

typeof 62;            // returns "number"

typeof 'Hello world'; // returns "string"

For property values, the typeof operator returns the type of value the property contains:

typeof document.lastModified; // returns "string"

typeof window.length;         // returns "number"

typeof Math.LN2;              // returns "number"

For methods and functions, the typeof operator returns results as follows:

typeof blur;        // returns "function"

typeof eval;        // returns "function"

typeof parseInt;    // returns "function"

typeof shape.split; // returns "function"

For predefined objects, the typeof operator returns results as follows:

typeof Date;     // returns "function"

typeof Function; // returns "function"

typeof Math;     // returns "object"

typeof Option;   // returns "function"

typeof String;   // returns "function"

void

The void operator is used in either of the following ways:

  1. void (expression)
  2. void expression

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.

You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.

The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to undefined, which has no effect in JavaScript.

<A HREF="javascript:void(0)">Click here to do nothing</A>

The following code creates a hypertext link that submits a form when the user clicks it.

<A HREF="javascript:void(document.form.submit())">

Click here to submit</A>

Operator precedence

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

The following table describes the precedence of operators, from highest to lowest.

In accordance with relevant discussion, this table was reversed to list operators in decreasing order of priority.

Table 3.7 Operator precedence

Operator type

Individual operators

member

. []

call / create instance

() new

negation/increment

! ~ - + ++ -- typeof void delete

multiply/divide

* / %

addition/subtraction

+ -

bitwise shift

<< >> >>>

relational

< <= > >= in instanceof

equality

== != === !==

bitwise-and

&

bitwise-xor

^

bitwise-or

|

logical-and

&&

logical-or

||

conditional

?:

assignment

= += -= *= /= %= <<= >>= >>>= &= ^= |=

comma

,

正则表达式

在本文章中

  1. 创建一个正则表达式
  2. 编写一个正则表达式的模式
  3. 使用简单的模式
  4. 使用特殊字符
  5. 使用插入语
  6. Working with Regular Expressions
  7. Using Parenthesized Substring Matches
  8. Example 1
  9. Advanced Searching With Flags
  10. 例子
  11. 改变输入字符串的顺序
  12. 用特殊字符检验输入

正则表达式是被用来匹配字符串中的字符组合的模式。在JavaScript中,正则表达式也是对象。这种模式可以被用于RegExpexectest方法以及 Stringmatchreplacesearchsplit方法。这一章介绍Javascript的正则表达式。

创建一个正则表达式

通过下面两种方法你可以创建一个正则表达式:

  • 使用一个正则表达式字面量,如下所示:

var re = /ab+c/;

正则表达式字面量在脚本加载后编译。若你的正则表达式是常量,使用这种方式可以获得更好的性能。

  • 调用RegExp对象的构造函数,如下所示:

var re = new RegExp("ab+c");

使用构造函数,提供了对正则表达式运行时的编译。当你知道正则表达式的模式会发生改变, 或者你事先并不了解它的模式或者是从其他地方(比如用户的输入),得到的代码这时比较适合用构造函数的方式。

编写一个正则表达式的模式

一个正则表达式模式是由简单的字符所构成的,比如/abc/, 或者是简单和特殊字符的组合,比如 /ab*c/ or /Chapter (\d+)\.\d*/. 最后一个例子用到了括号,它在正则表达式中可以被用做是一个记忆设备。这一部分正则所匹配的字符将会被记住,在后面可以被利用。正如 Using Parenthesized Substring Matches

使用简单的模式

简单的模式是有你找到的直接匹配所构成的。比如,/abc/这个模式就匹配了在一个字符串中,仅仅字符'abc'同时出现并按照这个顺序。在Hi, do you know your abc's?" 和 "The latest airplane designs evolved from slabcraft."就会匹配成功。在上面的两个实例中,匹配的是子字符串‘abc’。在字符串"Grab crab"中将不会被匹配,因为它不包含任何的‘abc’子字符串。

使用特殊字符

当你需要搜索一个比直接匹配需要更多条件的匹配时,比如寻找一个或多个b's,或者寻找空格,那么这时模式将要包含特殊字符。比如, 模式/ab*c/匹配了一个单独的‘a’后面跟了零个或则多个b(*的意思是前面一项出现了零个或者多个),且后面跟着‘c’的任何字符组合。在字符串“cbbabbbbcdebc,”中,这个模式匹配了子字符串'abbbbc'。

下面的表格列出了一个我们在正则表达式中可以利用的特殊字符的完整列表和描述。

表 4.1 正则表达式中的特殊字符

字符

含义

\

匹配下面之一

  • For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally.
  • For example, /b/ matches the character 'b'. By placing a backslash in front of b, that is by using /\b/, the character becomes special to mean match a word boundary.
  • 对于其后的平常被当作字面量的字符,将其转义为特殊字符。
  • 比如,/b/匹配了字符'b'.通过在b的前面放一个反斜杠,即用作/\b/,这个字符变成了一个特殊意义的字符,意思是匹配一个word boundary character
  •  
  • 对于其后的特殊字符,将其转义为字面量。
  •  
  • 比如,* 是一个代表着前一项0次或多次发生时将会被匹配的特殊字符;比如,/a*/代表会匹配0个或者多个a。为了匹配*号直接量,在它的前面加一个反斜杠;比如,/a\*/匹配'a*'
  •  
  • 当使用new RegExp("pattern")方法的时候不要忘记将\它自己进行转义,因为\在字符串里面也是一个转义字符。

^

匹配输入的开始。如果多行标示被设置为true,同时匹配换行后紧跟的字符。

比如,/^A/并不会匹配“an A”中的‘A’,但是会匹配“An E”中的‘A’。

当这个字符出现在一个字符集合模式的第一个字符的时候,它将会有不同的意义。

比如,/[^a-z\s]/会匹配“my 3 sisters”中的‘3’

$

匹配输入的结束,如果多行标示被设置为true,同时会匹配换行前紧跟的字符。

比如,/t$/并不会匹配“eater”中的‘t’,但是会匹配“eat”中的。

*

匹配前一个字符0次或者是多次。

比如,/bo*/会匹配“A ghost boooooed”中的'boooo'和‘A bird warbled’中的‘b’,但是在“A goat grunted”中将不会匹配任何东西。

+

匹配前面一个字符1次或者多次,和{1,}有相同的效果。

比如,/a+/匹配了在“candy”中的a,和在"caaaaaaandy"中所有的a。

?

Also used in lookahead assertions, described under x(?=y) and x(?!y) in this table.

匹配前面一个字符0次或者1次,和{0,1}有相同的效果。

比如,/e?le?/匹配“angel”中的‘el’,和"angle"中的‘le’以及“oslo”中的'l'。

如果'?'紧跟在在任何量词*, + , ?,或者是{}的后面,将会使量词变成非贪婪模式(匹配最少的次数),和默认的贪婪模式(匹配最多的次数)正好相反。比如,使用/\d+/非全局的匹配“123abc”将会返回“123”,如果使用/\d+?/,那么久只会匹配到“1”。

同时运用在向前断言,在本表的x(?=y)和x(?!y)中有描述。

.

(小数点)匹配任何除了新一行开头字符的任何单个字符。

比如,/.n/将会匹配‘nay, an apple is on the tree’中的‘an’和‘on’,但是不会匹配'nay'。

(x)

匹配‘x’并且记住匹配项。这个被叫做捕获括号。

比如,/(foo)/匹配和记住了“foo bar”中的'foo'。匹配到子字符串可以通过结果数组的[1],...,[n]元素进行访问。

(?:x)

匹配'x'但是不记住匹配项。这种被叫做非捕获括号。匹配到的子字符串不能通过结果数组的[1],...,[n]进行访问。

x(?=y)

匹配'x'仅仅当'x'后面跟着'y'.这种叫做正向肯定查找。

比如,/Jack(?=Sprat)/会匹配到'Jack'仅仅当它后面跟着'Sprat'。/Jack(?=Sprat|Frost)/匹配‘Jack’仅仅当它后面跟着'Sprat'或者是‘Frost’。但是‘Sprat’和‘Frost’都不是匹配结果的一部分。

x(?!y)

匹配'x'仅仅当'x'后面不跟着'y',这个叫做正向否定查找。

比如,/\d+(?!\.)/匹配一个数字仅仅当这个数字后面没有跟小数点的时候。正则表达式/\d+(?!\.)/.exec("3.141")匹配‘141’但是不是‘3.141’

x|y

匹配‘x’或者‘y’。

比如,/green|red/匹配“green apple”中的‘green’和“red apple”中的‘red’

{n}

n是一个正整数,匹配了前面一个字符刚好发生了n次。

比如,/a{2}/不会匹配“candy”中的'a',但是会匹配“caandy”中所有的a,以及“caaandy”中的前两个'a'。

{n,m}

n 和 m 都是正整数。匹配前面的字符至少n次,最多m次。如果 n 或者 m 的值是0, 这个值被忽略。

例如,/a{1, 3}/ 并不匹配“cndy”中得任意字符,匹配“candy”中得a,匹配“caandy”中得前两个a,也匹配“caaaaaaandy”中得前三个a。注意,当匹配”caaaaaaandy“时,匹配的值是“aaa”,即使原始的字符串中有更多的a。

[xyz]

一个字符集合。匹配方括号的中任意字符。你可以使用破折号(-)来指定一个字符范围。对于点(.)和星号(*)这样的特殊符号在一个字符集中没有特殊的意义。他们不必进行转意,不过转意也是起作用的。

例如,[abcd] 和[a-d]是一样的。他们都匹配"brisket"中得‘b’,也都匹配“city”中的‘c’。/[a-z.]+/ 和/[\w.]+/都匹配“test.i.ng”中得所有字符。

[^xyz]

一个反向字符集。也就是说, 它匹配任何没有包含在方括号中的字符。你可以使用破折号(-)来指定一个字符范围。任何普通字符在这里都是起作用的。

例如,[^abc] 和 [^a-c] 是一样的。他们匹配"brisket"中得‘r’,也匹配“chop”中的‘h’。

[\b]

匹配一个退格(U+0008)。(不要和\b混淆了。)

\b

匹配一个词的边界。一个词的边界就是一个词不被另外一个词跟随的位置或者不是另一个词汇字符前边的位置。注意,一个匹配的词的边界并不包含在匹配的内容中。换句话说,一个匹配的词的边界的内容的长度是0。(不要和[\b]混淆了)

例子:

/\bm/匹配“moon”中得‘m’;

/oo\b/并不匹配"moon"中得'oo',因为'oo'被一个词汇字符'n'紧跟着。

/oon\b/匹配"moon"中得'oon',因为'oon'是这个字符串的结束部分。这样他没有被一个词汇字符紧跟着。

/\w\b\w/将不能匹配任何字符串,因为一个单词中的字符永远也不可能被一个非词汇字符和一个词汇字符同时紧跟着。

\B

匹配一个非单词边界。他匹配一个前后字符都是相同类型的位置:都是单词或者都不是单词。一个字符串的开始和结尾都被认为是非单词。

例如,/\B../匹配"noonday"中得'oo', 而/y\B./匹配"possibly yesterday"中得’ye‘

\cX

当X是处于A到Z之间的字符的时候,匹配字符串中的一个控制符。

当X是处于A到Z之间的字符的时候,匹配字符串中的一个控制符。

例如,/\cM/ 匹配字符串中的 control-M (U+000D)。

\d

匹配一个数字。

等价于[0-9]。

例如, /\d/ 或者 /[0-9]/ 匹配"B2 is the suite number."中的'2'。

\D

匹配一个非数字字符。

等价于[^0-9]。

例如, /\D/ 或者 /[^0-9]/ 匹配"B2 is the suite number."中的'B' 。

\f

匹配一个换页符 (U+000C)。

\n

匹配一个换行符 (U+000A)。

\r

匹配一个回车符 (U+000D)。

\s

匹配一个空白字符,包括空格、制表符、换页符和换行符。

等价于[ \f\n\r\t\v​\u00A0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​\u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​\u2028\u2029​\u202f\u205f​\u3000]。

例如, /\s\w*/ 匹配"foo bar."中的' bar'。

\S

匹配一个非空白字符。

等价于[^ \f\n\r\t\v​\u00A0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​\u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​\u2028\u2029​\u202f\u205f​\u3000]。

例如, /\S\w*/ 匹配"foo bar."中的'foo'。

\t

匹配一个水平制表符 (U+0009)。

\v

匹配一个垂直制表符 (U+000B)。

\w

匹配一个单字字符(字母、数字或者下划线)。

等价于[A-Za-z0-9_]。

例如, /\w/ 匹配 "apple," 中的 'a',"$5.28,"中的 '5' 和 "3D." 中的 '3'。

\W

匹配一个非单字字符。

等价于[^A-Za-z0-9_]。

例如, /\W/ 或者 /[^A-Za-z0-9_]/ 匹配 "50%." 中的 '%'。

\n

当 n 是一个正整数,一个返回引用到最后一个与有n插入的正值表达式(counting left parentheses)匹配的副字符串。

Where n is a positive integer, a back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses).

比如 /apple(,)\sorange\1/ 匹配 'apple, orange,' in "apple, orange, cherry, peach."

\0

匹配 NULL (U+0000) character. 不要在这后面跟其它小数,因为 \0<digits> 是一个八进制转义序列。

\xhh

匹配带有两位小数代码(hh)的字符

\uhhhh

匹配带有四位小数代码(hh)的字符

有些转义用户输入被处理成含有一个正值表达式的字面字符串,这些输入可以被简单的替代值补充完整。

function escapeRegExp(string){

  return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, "\\$1");

}

使用插入语

任何正值表达式的插入语都会使这部分匹配的副字符串被记忆。一旦被记忆,这个副字符串就可以被调用于其它用途,如同 Using Parenthesized Substring Matches之中所述。

比如, /Chapter (\d+)\.\d*/ 解释了额外逸出的和特殊的字符,并说明了这部分pattern应该被记忆。它精确地匹配后面跟着一个以上数字字符的字符 'Chapter '  (\d 意为任何数字字符,+ 意为1次以上),跟着一个小数点(在这个字符中本身也是一个特殊字符;小数点前的 \ 意味着这个pattern必须寻找字面字符 '.'),跟着任何数字字符0次以上。 (\d 意为数字字符, * 意为0次以上)。另外,插入语也用来记忆第一个匹配的数字字符。

This pattern is found in "Open Chapter 4.3, paragraph 6" and '4' is remembered. The pattern is not found in "Chapter 3 and 4", because that string does not have a period after the '3'.

To match a substring without causing the matched part to be remembered, within the parentheses preface the pattern with ?:. For example, (?:\d+) matches one or more numeric characters but does not remember the matched characters.

Working with Regular Expressions

Regular expressions are used with the RegExp methods test and exec and with the String methods match, replace, search, and split. These methods are explained in detail in the JavaScript Reference.

Table 4.2 Methods that use regular expressions

Method

Description

exec

A RegExp method that executes a search for a match in a string. It returns an array of information.

test

A RegExp method that tests for a match in a string. It returns true or false.

match

A String method that executes a search for a match in a string. It returns an array of information or null on a mismatch.

search

A String method that tests for a match in a string. It returns the index of the match, or -1 if the search fails.

replace

A String method that executes a search for a match in a string, and replaces the matched substring with a replacement substring.

split

A String method that uses a regular expression or a fixed string to break a string into an array of substrings.

When you want to know whether a pattern is found in a string, use the test or search method; for more information (but slower execution) use the exec ormatch methods. If you use exec or match and if the match succeeds, these methods return an array and update properties of the associated regular expression object and also of the predefined regular expression object, RegExp. If the match fails, the exec method returns null (which converts to false).

In the following example, the script uses the exec method to find a match in a string.

var myRe = /d(b+)d/g;

var myArray = myRe.exec("cdbbdbsbz");

If you do not need to access the properties of the regular expression, an alternative way of creating myArray is with this script:

var myArray = /d(b+)d/g.exec("cdbbdbsbz");

If you want to construct the regular expression from a string, yet another alternative is this script:

var myRe = new RegExp("d(b+)d", "g");

var myArray = myRe.exec("cdbbdbsbz");

With these scripts, the match succeeds and returns the array and updates the properties shown in the following table.

Table 4.3 Results of regular expression execution.

Object

Property or index

Description

In this example

myArray

 

The matched string and all remembered substrings.

["dbbd", "bb"]

index

The 0-based index of the match in the input string.

1

input

The original string.

"cdbbdbsbz"

[0]

The last matched characters.

"dbbd"

myRe

lastIndex

The index at which to start the next match. (This property is set only if the regular expression uses the g option, described in Advanced Searching With Flags.)

5

source

The text of the pattern. Updated at the time that the regular expression is created, not executed.

"d(b+)d"

As shown in the second form of this example, you can use a regular expression created with an object initializer without assigning it to a variable. If you do, however, every occurrence is a new regular expression. For this reason, if you use this form without assigning it to a variable, you cannot subsequently access the properties of that regular expression. For example, assume you have this script:

var myRe = /d(b+)d/g;

var myArray = myRe.exec("cdbbdbsbz");

console.log("The value of lastIndex is " + myRe.lastIndex);

This script displays:

The value of lastIndex is 5

However, if you have this script:

var myArray = /d(b+)d/g.exec("cdbbdbsbz");

console.log("The value of lastIndex is " + /d(b+)d/g.lastIndex);

It displays:

The value of lastIndex is 0

The occurrences of /d(b+)d/g in the two statements are different regular expression objects and hence have different values for their lastIndex property. If you need to access the properties of a regular expression created with an object initializer, you should first assign it to a variable.

Using Parenthesized Substring Matches

Including parentheses in a regular expression pattern causes the corresponding submatch to be remembered. For example, /a(b)c/ matches the characters 'abc' and remembers 'b'. To recall these parenthesized substring matches, use the Array elements [1], ..., [n].

The number of possible parenthesized substrings is unlimited. The returned array holds all that were found. The following examples illustrate how to use parenthesized substring matches.

Example 1

The following script uses the replace() method to switch the words in the string. For the replacement text, the script uses the $1 and $2 in the replacement to denote the first and second parenthesized substring matches.

var re = /(\w+)\s(\w+)/;

var str = "John Smith";

var newstr = str.replace(re, "$2, $1");

console.log(newstr);

This prints "Smith, John".

Advanced Searching With Flags

Regular expressions have four optional flags that allow for global and case insensitive searching. To indicate a global search, use the g flag. To indicate a case-insensitive search, use the i flag. To indicate a multi-line search, use the m flag. To perform a "sticky" search, that matches starting at the current position in the target string, use the y flag. These flags can be used separately or together in any order, and are included as part of the regular expression.

Firefox 3 note

Support for the y flag was added in Firefox 3. The y flag fails if the match doesn't succeed at the current position in the target string.

To include a flag with the regular expression, use this syntax:

var re = /pattern/flags;

or

var re = new RegExp("pattern", "flags");

Note that the flags are an integral part of a regular expression. They cannot be added or removed later.

For example, re = /\w+\s/g creates a regular expression that looks for one or more characters followed by a space, and it looks for this combination throughout the string.

var re = /\w+\s/g;

var str = "fee fi fo fum";

var myArray = str.match(re);

console.log(myArray);

This displays ["fee ", "fi ", "fo "]. In this example, you could replace the line:

var re = /\w+\s/g;

with:

var re = new RegExp("\\w+\\s", "g");

and get the same result.

The m flag is used to specify that a multiline input string should be treated as multiple lines. If the m flag is used, ^ and $ match at the start or end of any line within the input string instead of the start or end of the entire string.

例子

以下例子说明了一些正值表达式的用途。

改变输入字符串的顺序

以下例子解释了正值表达式的构成和string.split() 以及 string.replace()的用途。它会整理一个只有粗略格式的含有全名(名字首先出现)的输入字符串,这个字符串被空格、换行符和一个分号分隔。最终,它会颠倒名字顺序(姓氏首先出现)和list的类型。

// The name string contains multiple spaces and tabs,

// and may have multiple spaces between first and last names.

var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ; Chris Hand ";

 

var output = ["---------- Original String\n", names + "\n"];

 

// Prepare two regular expression patterns and array storage.

// Split the string into array elements.

 

// pattern: possible white space then semicolon then possible white space

var pattern = /\s*;\s*/;

 

// Break the string into pieces separated by the pattern above and

// store the pieces in an array called nameList

var nameList = names.split(pattern);

 

// new pattern: one or more characters then spaces then characters.

// Use parentheses to "memorize" portions of the pattern.

// The memorized portions are referred to later.

pattern = /(\w+)\s+(\w+)/;

 

// New array for holding names being processed.

var bySurnameList = [];

 

// Display the name array and populate the new array

// with comma-separated names, last first.

//

// The replace method removes anything matching the pattern

// and replaces it with the memorized string—second memorized portion

// followed by comma space followed by first memorized portion.

//

// The variables $1 and $2 refer to the portions

// memorized while matching the pattern.

 

output.push("---------- After Split by Regular Expression");

 

var i, len;

for (i = 0, len = nameList.length; i < len; i++){

  output.push(nameList[i]);

  bySurnameList[i] = nameList[i].replace(pattern, "$2, $1");

}

 

// Display the new array.

output.push("---------- Names Reversed");

for (i = 0, len = bySurnameList.length; i < len; i++){

  output.push(bySurnameList[i]);

}

 

// Sort by last name, then display the sorted array.

bySurnameList.sort();

output.push("---------- Sorted");

for (i = 0, len = bySurnameList.length; i < len; i++){

  output.push(bySurnameList[i]);

}

 

output.push("---------- End");

 

console.log(output.join("\n"));

用特殊字符检验输入

在以下例子中,我们期望用户输入一个电话号码。当用户点击“Check”按钮,我们的脚本开始检查这些数字是否合法。如果数字合法(匹配正值表达式所规定的字符序列),脚本显示一条感谢用户的信息并确认该数字。如果这串数字不合法,脚本提示用户电话号码不合法。.

包含非捕获插入语 (?: ,这个正值表达式寻找三个数字字符\d{3} OR | a left parenthesis \(跟着三位小数 \d{3}, 跟着一个封闭插入语 \), (结束非捕获插入语 )), 跟着一个右斜杠或左斜杠或小数点;当它找到三个数字字符,记忆字符 ([-\/\.]),跟着三位小数 \d{3},跟着记住的左斜杠、右斜杠或小数点 \1,跟着四位小数 \d{4}。

当用户按下Enter设置RegExp.input,这些变化也能被激活。

<!DOCTYPE html>

<html> 

  <head> 

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 

    <meta http-equiv="Content-Script-Type" content="text/javascript"> 

    <script type="text/javascript"> 

      var re = /\(?\d{3}\)?([-\/\.])\d{3}\1\d{4}/; 

      function testInfo(phoneInput){ 

        var OK = re.exec(phoneInput.value); 

        if (!OK) 

          window.alert(RegExp.input + " isn't a phone number with area code!"); 

        else

          window.alert("Thanks, your phone number is " + OK[0]); 

      } 

    </script> 

  </head> 

  <body> 

    <p>Enter your phone number (with area code) and then click "Check".

        <br>The expected format is like ###-###-####.</p>

    <form action="#"> 

      <input id="phone"><button onclick="testInfo(document.getElementById('phone'));">Check</button>

    </form> 

  </body> 

</html>

 

语句

在本文章中

  1. 区块语句(Block Statement)
  2. 条件语句(Conditional Statements)
  3. if...else 语句
  4. 开关语句(Switch Statement)
  5. 循环语句(Loop Statement)
  6. for语句(for Statement)
  7. do...while 语句
  8. while 语句
  9. 标签语句(label Statement)
  10. 中断语句(break Statement)
  11. 连续语句(continue Statement)
  12. 对象操作语句(Object Manipulation Statements)
  13. for each...in 语句
  14. 批注(Comments)
  15. 异常处理语句(Exception Handling Statements)
  16. Exception Types
  17. 抛出语句(throw Statement)
  18. try...catch 语句
  19. The catch Block
  20. The finally Block
  21. Nesting try...catch Statements
  22. Utilizing Error objects

这篇翻译不完整。请帮忙从英语翻译这篇文章

JavaScript 支持一系列精简的语句,你可以用它们使你的网页充满互动。这一章节我们将带来关于语句的概览。.

任何表达式都同时是一个语句。参见 Expressions and Operators 获得关于语句的完整信息。

你可以使用分号(;) 字符在Java Script代码中分隔语句。

参见 JavaScript Reference 获得关于本章中语句的详细信息。

区块语句(Block Statement

区块语句用于给语句分组。我们用一对花括号划分区块。

{

   statement_1;

   statement_2;

   .

   .

   .

   statement_n;

}

Example
区块语句一般和控制流语句(control flow statements,例如if, for, while)一起使用。

while (x < 10){

  x++;

}

这里,{ x++; } 就是区块语句。

Important: JavaScript does not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java. For example:

var x = 1;

{

  var x = 2;

}

alert(x); // outputs 2

This outputs 2 because the var x statement within the block is in the same scope as the var x statement before the block. In C or Java, the equivalent code would have outputted 1.

条件语句(Conditional Statements

条件语句是一系列当指定条件为真时执行的命令。JavaScript支持两种条件语句:if...else 和 switch。

if...else 语句

当一个逻辑条件为真,用if语句执行一个语句。当这个条件为假,使用可选择的else从句来执行这个语句。if语句如下所示:

if (condition)

  statement_1

[else

  statement_2]

condition can be any expression that evaluates to true or false. If condition evaluates to true, statement_1 is executed; otherwise, statement_2 is executed. statement_1 and statement_2 can be any statement, including further nested if statements.

You may also compound the statements using else if to have multiple conditions tested in sequence, as follows:

if (condition)

  statement_1

[else if (condition_2)

  statement_2]

...

[else if (condition_n_1)

  statement_n_1]

[else

  statement_n]

To execute multiple statements, use a block statement ({ ... }) to group those statements. In general, it is a good practice to always use block statements, especially in code involving nested if statements:

if (condition) {

  statements_1

} else {

  statements_2

}

It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:

if (x = y) {

  /* do the right thing */

}

If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:

if ((x = y)) {

  /* do the right thing */

}

The following values will evaluate to false:

  • false
  • undefined
  • null
  • 0
  • NaN
  • the empty string ("")

All other values, including all objects evaluate to true when passed to a conditional statement.

Do not confuse the primitive boolean values true and false with the true and false values of the Boolean object. For example:

var b = new Boolean(false);

if (b) // this condition evaluates to true

Example
In the following example, the function checkData returns true if the number of characters in a Text object is three; otherwise, it displays an alert and returns false.

function checkData() {

  if (document.form1.threeChar.value.length == 3) {

    return true;

  } else {

    alert("Enter exactly three characters. " +

      document.form1.threeChar.value + " is not valid.");

    return false;

  }

}

开关语句(Switch Statement)

开关语句允许一个程序求一个表达式的值并且尝试去匹配表达式的值到一个case label。如果匹配成功,这个程序执行相关的语句。开关语句如下所示:

A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement. A switch statement looks as follows:

switch (expression) {

   case label_1:

      statements_1

      [break;]

   case label_2:

      statements_2

      [break;]

   ...

   default:

      statements_def

      [break;]

}

The program first looks for a case clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements. If no matching label is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, thedefault clause is the last clause, but it does not need to be so.

The optional break statement associated with each case clause ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

Example
In the following example, if fruittype evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program terminates switch and executes the statement following switch. If break were omitted, the statement for case "Cherries" would also be executed.

switch (fruittype) {

   case "Oranges":

      document.write("Oranges are $0.59 a pound.<br>");

      break;

   case "Apples":

      document.write("Apples are $0.32 a pound.<br>");

      break;

   case "Bananas":

      document.write("Bananas are $0.48 a pound.<br>");

      break;

   case "Cherries":

      document.write("Cherries are $3.00 a pound.<br>");

      break;

   case "Mangoes":

   case "Papayas":

      document.write("Mangoes and papayas are $2.79 a pound.<br>");

      break;

   default:

      document.write("Sorry, we are out of " + fruittype + ".<br>");

}

document.write("Is there anything else you'd like?<br>");

循环语句(Loop Statement

循环语句是一系列反复执行直到符合特定条件的命令。JavaScript 支持 for, do while, while这些循环语句,还有Label (label 本身不是一个循环语句,但是经常和这些语句一起使用)。另外,你可以在循环语句中使用break和continue 语句 。

另一个语句:for...in也反复执行语句,但它是用来操作对象的。参见 Object Manipulation Statements

The loop statements are:

for语句(for Statement)

for 循环反复直到一个特定的条件计算为假。JavaScript中的循环和Java以及C中的循环相似。for语句如下所示:

for ([initialExpression]; [condition]; [incrementExpression])

   statement

When a for loop executes, the following occurs:

  1. The initializing expression initialExpression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.
  2. The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates. If the condition expression is omitted entirely, the condition is assumed to be true.
  3. The statement executes. To execute multiple statements, use a block statement ({ ... }) to group those statements.
  4. The update expression incrementExpression, if there is one, executes, and control returns to step 2.

Example
The following function contains a for statement that counts the number of selected options in a scrolling list (a Select object that allows multiple selections). The for statement declares the variable i and initializes it to zero. It checks that i is less than the number of options in the Select object, performs the succeeding if statement, and increments i by one after each pass through the loop.

<script type="text/javascript">

 

function howMany(selectObject) {

   var numberSelected = 0;

   for (var i = 0; i < selectObject.options.length; i++) {

      if (selectObject.options[i].selected)

         numberSelected++;

   }

   return numberSelected;

}

 

</script>

<form name="selectForm">

   <p>

      <strong>Choose some music types, then click the button below:</strong>

      <br/>

      <select name="musicTypes" multiple="multiple">

         <option selected="selected">R&B</option>

         <option>Jazz</option>

         <option>Blues</option>

         <option>New Age</option>

         <option>Classical</option>

         <option>Opera</option>

      </select>

   </p>

   <p>

      <input type="button" value="How many are selected?"

         onclick="alert ('Number of options selected: ' + howMany(document.selectForm.musicTypes))"/>

   </p>

</form>

do...while 语句

do...while 语句反复直到一个特定条件计算为假。do...while 语句如下所示:

do

   statement

while (condition);

statement executes once before the condition is checked. To execute multiple statements, use a block statement ({ ... }) to group those statements. Ifcondition is true, the statement executes again. At the end of every execution, the condition is checked. When the condition is false, execution stops and control passes to the statement following do...while.

Example
In the following example, the do loop iterates at least once and reiterates until i is no longer less than 5.

do {

   i += 1;

   document.write(i);

} while (i < 5);

while 语句

while语句只要一个特定条件计算为真就执行语句。如下所示:

while (condition)

   statement

If the condition becomes false, statement within the loop stops executing and control passes to the statement following the loop.

The condition test occurs before statement in the loop are executed. If the condition returns true, statement is executed and the condition is tested again. If the condition returns false, execution stops and control is passed to the statement following while.

To execute multiple statements, use a block statement ({ ... }) to group those statements.

Example 1
The following while loop iterates as long as n is less than three:

n = 0;

x = 0;

while (n < 3) {

   n++;

   x += n;

}

With each iteration, the loop increments n and adds that value to x. Therefore, x and n take on the following values:

  • After the first pass: n = 1 and x = 1
  • After the second pass: n = 2 and x = 3
  • After the third pass: n = 3 and x = 6

After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.

Example 2
Avoid infinite loops. Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate. The statements in the followingwhile loop execute forever because the condition never becomes false:

while (true) {

   alert("Hello, world");

}

标签语句(label Statement)

标签语句提供一种使你同一程序的在另一处找到它的标识。例如,你可以用一个标签来识别一个循环,并用break或continue语句来说明一个程序是否要中断这个循环或是继续执行。如下所示:

label :

   statement

The value of label may be any JavaScript identifier that is not a reserved word. The statement that you identify with a label may be any statement.

Example
In this example, the label markLoop identifies a while loop.

markLoop:

while (theMark == true) {

   doSomething();

}

中断语句(break Statement)

使用中断语句终止循环、开关或与标签语句连接。

  • When you use break without a label, it terminates the innermost enclosing while, do-while, for, or switch immediately and transfers control to the following statement.
  • When you use break with a label, it terminates the specified labeled statement.

The syntax of the break statement looks like this:

  1. break;
  2. break label;

The first form of the syntax terminates the innermost enclosing loop or switch; the second form of the syntax terminates the specified enclosing label statement.

Example 1:
The following example iterates through the elements in an array until it finds the index of an element whose value is theValue:

for (i = 0; i < a.length; i++) {

   if (a[i] == theValue)

      break;

}

Example 2: Breaking to a Label

var x = 0;

var z = 0

labelCancelLoops: while (true) {

    console.log("Outer loops: " + x);

    x += 1;

    z = 1;

    while (true) {

        console.log("Inner loops: " + z);

        z += 1;

        if (z === 10 && x === 10) {

            break labelCancelLoops;

        } else if (z === 10) {

            break;

        }

    }

}

连续语句(continue Statement)

连续语句用于重新开始 while, do-while, for语句,或者标签语句(label statement).

  • When you use continue without a label, it terminates the current iteration of the innermost enclosing while, do-while or for statement and continues execution of the loop with the next iteration. In contrast to the break statement, continue does not terminate the execution of the loop entirely. In awhile loop, it jumps back to the condition. In a for loop, it jumps to the increment-expression.
  • When you use continue with a label, it applies to the looping statement identified with that label.

The syntax of the continue statement looks like the following:

  1. continue
  2. continue label

Example 1
The following example shows a while loop with a continue statement that executes when the value of i is three. Thus, n takes on the values one, three, seven, and twelve.

i = 0;

n = 0;

while (i < 5) {

   i++;

   if (i == 3)

      continue;

   n += i;

}

Example 2
A statement labeled checkiandj contains a statement labeled checkj. If continue is encountered, the program terminates the current iteration of checkj and begins the next iteration. Each time continue is encountered, checkj reiterates until its condition returns false. When false is returned, the remainder of the checkiandj statement is completed, and checkiandj reiterates until its condition returns false. When false is returned, the program continues at the statement following checkiandj.

If continue had a label of checkiandj, the program would continue at the top of the checkiandj statement.

checkiandj :

   while (i < 4) {

      document.write(i + "<br/>");

      i += 1;

      checkj :

         while (j > 4) {

            document.write(j + "<br/>");

            j -= 1;

            if ((j % 2) == 0)

               continue checkj;

            document.write(j + " is odd.<br/>");

         }

      document.write("i = " + i + "<br/>");

      document.write("j = " + j + "<br/>");

   }

对象操作语句(Object Manipulation Statements

JavaScript 用 for...in, for each...in和 with语句来操作对象。

Object Manipulation Statement

The for...in statement iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements. A for...in statement looks as follows:

for (variable in object) {

   statements

}

Example
The following function takes as its argument an object and the object's name. It then iterates over all the object's properties and returns a string that lists the property names and their values.

function dump_props(obj, obj_name) {

   var result = "";

   for (var i in obj) {

      result += obj_name + "." + i + " = " + obj[i] + "<br>";

   }

   result += "<hr>";

   return result;

}

For an object car with properties make and model, result would be:

car.make = Ford

car.model = Mustang

Arrays
Although it may be tempting to use this as a way to iterate over Array elements, because the for...in statement iterates over user-defined properties in addition to the array elements, if you modify the Array object, such as adding custom properties or methods, the for...in statement will return the name of your user-defined properties in addition to the numeric indexes. Thus it is better to use a traditional for loop with a numeric index when iterating over arrays.

for each...in 语句

for each...in 是一种在 JavaScript 1.6介绍过的循环语句。它和for...in相似,但是让对象属性的值递回取得,而不是作用于它们的名字。

var sum = 0;

var obj = {prop1: 5, prop2: 13, prop3: 8};

for each (var item in obj) {

  sum += item;

}

print(sum); // prints "26", which is 5+13+8

批注(Comments)

批注是作者解释脚本的记号。批注会被interpreter忽略。 JavaScript支持Java 和C++-式样的批注:

  • Comments on a single line are preceded by a double-slash (//).
  • Comments that span multiple lines are preceded by /* and followed by */:

Example
The following example shows two comments:

// This is a single-line comment.

 

/* This is a multiple-line comment. It can be of any length, and

you can put whatever you want here. */

异常处理语句(Exception Handling Statements)

你可以用throw statement抛出一个例外并且用try...catch statements处理它。

You can also use the try...catch statement to handle Java exceptions (though there is a bug 391642 with this). See Handling Java Exceptions in JavaScriptand JavaScript to Java Communication for information.

Exception Types

Just about any object can be thrown in JavaScript. Nevertheless, not all thrown objects are created equal. While it is fairly common to throw numbers or strings as errors it is frequently more effective to use one of the exception types specifically created for this purpose:

抛出语句(throw Statement)

使用抛出语句抛出一个例外。当你抛出例外,你规定一个含有值的表达式要被抛出。

throw expression;

You may throw any expression, not just expressions of a specific type. The following code throws several exceptions of varying types:

throw "Error2";

throw 42;

throw true;

throw {toString: function() { return "I'm an object!"; } };

Note: You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object myUserException of type UserException and uses it in a throw statement.

// Create an object type UserException

function UserException (message){

  this.message=message;

  this.name="UserException";

}

 

// Make the exception convert to a pretty string when used as

// a string (e.g. by the error console)

UserException.prototype.toString = function (){

  return this.name + ': "' + this.message + '"';

}

 

// Create an instance of the object type and throw it

throw new UserException("Value too high");

try...catch 语句

try...catch 语句标记一块待尝试的语句,并规定一个以上的响应应该有一个例外被抛出。如果我们抛出一个例外,try...catch语句就接住它。

The try...catch statement consists of a try block, which contains one or more statements, and zero or more catch blocks, containing statements that specify what to do if an exception is thrown in the try block. That is, you want the try block to succeed, and if it does not succeed, you want control to pass to the catch block. If any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to thecatch block. If no exception is thrown in the try block, the catch block is skipped. The finally block executes after the try and catch blocks execute but before the statements following the try...catch statement.

The following example uses a try...catch statement. The example calls a function that retrieves a month name from an array based on the value passed to the function. If the value does not correspond to a month number (1-12), an exception is thrown with the value "InvalidMonthNo" and the statements in thecatch block set the monthName variable to unknown.

function getMonthName (mo) {

    mo=mo-1; // Adjust month number for array index (1=Jan, 12=Dec)

    var months=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul",

          "Aug","Sep","Oct","Nov","Dec");

    if (months[mo] != null) {

       return months[mo]

    } else {

       throw "InvalidMonthNo"

    }

}

 

try {

// statements to try

    monthName=getMonthName(myMonth) // function could throw exception

}

catch (e) {

    monthName="unknown"

    logMyErrors(e) // pass exception object to error handler

}

The catch Block

You can use a catch block to handle all exceptions that may be generated in the try block.

catch (catchID) {

  statements

}

The catch block specifies an identifier (catchID in the preceding syntax) that holds the value specified by the throw statement; you can use this identifier to get information about the exception that was thrown. JavaScript creates this identifier when the catch block is entered; the identifier lasts only for the duration of the catch block; after the catch block finishes executing, the identifier is no longer available.

For example, the following code throws an exception. When the exception occurs, control transfers to the catch block.

try {

   throw "myException" // generates an exception

}

catch (e) {

// statements to handle any exceptions

   logMyErrors(e) // pass exception object to error handler

}

The finally Block

The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catchblock handles the exception.

You can use the finally block to make your script fail gracefully when an exception occurs; for example, you may need to release a resource that your script has tied up. The following example opens a file and then executes statements that use the file (server-side JavaScript allows you to access files). If an exception is thrown while the file is open, the finally block closes the file before the script fails.

openMyFile();

try {

    writeMyFile(theData); //This may throw a error

}catch(e){

    handleError(e); // If we got a error we handle it

}finally {

    closeMyFile(); // always close the resource

}

If the finally block returns a value, this value becomes the return value of the entire try-catch-finally production, regardless of any return statements in the try and catch blocks:

function f() {

    try {

        alert(0);

        throw "bogus";

    } catch(e) {

        alert(1);

        return true; // this return statement is suspended until finally block has completed

        alert(2); // not reachable

    } finally {

        alert(3);

        return false; // overwrites the previous "return"

        alert(4); // not reachable

    }

    // "return false" is executed now

   

    alert(5); // not reachable

}

f(); // alerts 0, 1, 3; returns false

Nesting try...catch Statements

You can nest one or more try...catch statements. If an inner try...catch statement does not have a catch block, the enclosing try...catch statement'scatch block is checked for a match.

Utilizing Error objects

Depending on the type of error, you may be able to use the 'name' and 'message' properties to get a more refined message. 'name' provides the general class of Error (e.g., 'DOMException' or 'Error'), while 'message' generally provides a more succinct message than one would get by converting the error object to a string.

If you are throwing your own exceptions, in order to take advantage of these properties (such as if your catch block doesn't discriminate between your own exceptions and system ones), you can use the Error constructor. For example:

function doSomethingErrorProne () {

   if (ourCodeMakesAMistake()) {

      throw (new Error('The message'));

   }

   else {

      doSomethingToGetAJavascriptError();

   }

}

....

try {

   doSomethingErrorProne();

}

catch (e) {

   alert(e.name);// alerts 'Error'

   alert(e.message); // alerts 'The message' or a JavaScript error message)

}

 

 

posted on 2014-12-04 10:23  nxp  阅读(211)  评论(0)    收藏  举报