Javascript 简明教程

JavaScript - Quick Guide

JavaScript - Overview

What is JavaScript ?

JavaScript 是一种动态计算机编程语言。它很轻量,最常用作网页的一部分,其实现允许客户端脚本与用户进行交互并制作动态页面。它是一种具有面向对象功能的解释性编程语言。

JavaScript 最初被称为 LiveScript, ,但 Netscape 将其名称改为 JavaScript,可能是因为 Java 产生的激昂。JavaScript 于 1995 年首次在 Netscape 2.0 中以 LiveScript 的名称出现。该语言的通用核心已嵌入 Netscape、Internet Explorer 和其他网络浏览器中。

ECMA-262 Specification 定义了核心 JavaScript 语言的标准版本。

  1. JavaScript 是一款轻量、解释性编程语言。

  2. 旨在创建以网络为中心的应用程序。

  3. 与 Java 互补并集成在一起。

  4. 与 HTML 互补并集成在内。

  5. Open and cross-platform

Client-Side JavaScript

客户端 JavaScript 是该语言最常用的形式。脚本应包含在 HTML 文档中或由其引用,这样浏览器才能解释该代码。

这意味着一个网页不必是静态 HTML,但可以包含与用户交互、控制浏览器和动态创建 HTML 内容的程序。

JavaScript 客户端机制比传统的 CGI 服务器端脚本提供了许多优势。例如,你可以使用 JavaScript 来检查用户是否在表单字段中输入了有效的电子邮件地址。

JavaScript 代码在用户提交表单时执行,并且只有在所有条目有效时,才会提交给 Web 服务器。

JavaScript 可用于捕获用户发起的事件,例如按钮点击、链接导航以及用户显式或隐式发起的其他操作。

Advantages of JavaScript

使用 JavaScript 的优点为 −

  1. Less server interaction - 在将页面发送到服务器之前,你可以验证用户输入。这可以节省服务器流量,这意味着服务器上的负载会变小。

  2. Immediate feedback to the visitors - 用户无需等待页面重新加载,即可查看自己是否忘记输入某些内容。

  3. Increased interactivity - 你可以创建在用户将鼠标悬停在它们上面或通过键盘激活它们时做出反应的界面。

  4. Richer interfaces - 你可以使用 JavaScript 来包括诸如拖放组件和滑块等项目,为你的网站访问者提供丰富的界面。

Limitations of JavaScript

我们不能将 JavaScript 当作一门成熟的编程语言。它缺少以下重要特性 −

  1. 客户端 JavaScript 不允许读写文件。这是出于安全考虑。

  2. JavaScript 无法用于网络应用程序,因为没有提供这种支持。

  3. JavaScript 没有任何多线程或多处理器功能。

再说一遍,JavaScript 是一种轻量级解释型编程语言,让你可以将交互性融入到原本静态的 HTML 页面中。

JavaScript Development Tools

JavaScript 的主要优点之一在于它不需要昂贵的开发工具。你可以从简单的文本编辑器(如记事本)开始。由于它是一种在 Web 浏览器上下文中解释的语言,你甚至不需要购买编译器。

为了让我们的生活更轻松,各种供应商推出了非常不错的 JavaScript 编辑工具。其中一些工具如下 −

  1. Microsoft FrontPage − Microsoft 开发了一款流行的 HTML 编辑器,称为 FrontPage。FrontPage 还为 Web 开发者提供了一些 JavaScript 工具,以协助创建交互式网站。

  2. Macromedia Dreamweaver MX − Macromedia Dreamweaver MX 是专业 Web 开发人员中非常流行的 HTML 和 JavaScript 编辑器。它提供了几个实用的预制 JavaScript 组件,并能与数据库很好地集成,同时还符合 XHTML 和 XML 等新标准。

  3. Macromedia HomeSite 5 − HomeSite 5 是 Macromedia 中一款广受欢迎的 HTML 和 JavaScript 编辑器,可以用它有效地管理个人网站。

Where is JavaScript Today ?

ECMAScript 第 5 版标准将是时隔四年发布的首次更新。JavaScript 2.0 符合 ECMAScript 标准第 5 版,而两者之间的区别非常微小。

JavaScript 2.0 的规范可以在以下网站上找到: https://www-archive.mozilla.org/js/language/js20-2002-04/

如今,Netscape 的 JavaScript 和 Microsoft 的 JScript 均符合 ECMAScript 标准,虽然这两种语言仍然支持不属于该标准的功能。

JavaScript - Syntax

JavaScript 可使用放置在网页 <script>…​ </script> HTML 标记中的 JavaScript 语句来实现。

你可以在网页中的任何位置放置包含 JavaScript 的 <script> 标记,但通常建议你将它包含在 <head> 标记中。

<script> 标记警示浏览器程序开始解读这些标记之间的所有文本作为脚本。你的 JavaScript 的一个简单语法将如下所示。

<script ...>
   JavaScript code
</script>

script 标记有两个重要的属性 −

  1. Language − 该属性指定你正在使用的脚本语言。通常,它的值为 javascript。虽然 HTML 的最新版本(及其后继者 XHTML)已逐步淘汰对此属性的使用。

  2. Type − 该属性是现在建议用来指示正在使用的脚本语言的,其值应设置为“text/javascript”。

因此,你的 JavaScript 代码段看起来像 −

<script language = "javascript" type = "text/javascript">
   JavaScript code
</script>

Your First JavaScript Code

让我们举一个打印“Hello World”的示例。我们添加了一个可选的 HTML 注释,该注释围绕我们的 JavaScript 代码。这是为了将我们的代码保存在不支持 JavaScript 的浏览器中。注释以“//-→”结尾。此处,“//”表示 JavaScript 中的注释,因此我们添加了该注释,以防止浏览器将 HTML 注释的结尾读取为 JavaScript 代码的一部分。接下来,我们调用一个函数 document.write ,该函数将一个字符串写入我们的 HTML 文档。

可以使用此函数来编写文本、HTML 或两者。请查看以下代码。

<html>
   <body>
      <script language = "javascript" type = "text/javascript">
         <!--
            document.write("Hello World!")
         //-->
      </script>
   </body>
</html>

此代码将产生以下结果 −

Hello World!

Whitespace and Line Breaks

JavaScript 忽略出现在 JavaScript 程序中空格、制表符和换行符。你可以在程序中自由地使用空格、制表符和换行符,并且可以自由地格式化和缩进你的程序,以一种清晰一致的方式,便于阅读和理解代码。

Semicolons are Optional

JavaScript 中的简单语句通常后跟一个分号字符,就像它们在 C、C++ 和 Java 中一样。但是,JavaScript 允许你省略此分号,如果你的每个语句都位于单独的行中。例如,可以编写没有分号的以下代码。

<script language = "javascript" type = "text/javascript">
   <!--
      var1 = 10
      var2 = 20
   //-->
</script>

但是,如果按如下方式格式化为单行,则你必须使用分号 −

<script language = "javascript" type = "text/javascript">
   <!--
      var1 = 10; var2 = 20;
   //-->
</script>

Note − 使用分号是一种良好的编程实践。

Case Sensitivity

JavaScript 是一种区分大小写的语言。这意味着语言关键字、变量、函数名和任何其他标识符都必须始终采用一致的大小写字母输入。

所以在 JavaScript 中,标识符 TimeTIME 将传达不同的含义。

NOTE − 在 JavaScript 中编写变量和函数名称时应小心。

Comments in JavaScript

JavaScript 既支持 C 样式注释,也支持 C++ 样式注释,即 -

  1. // 和行尾之间的任何文本都被视为注释,并被 JavaScript 忽略。

  2. /* 和 */ 之间的任何文本都被视为注释。这可能跨越多行。

  3. JavaScript 也识别 HTML 注释开头序列 <!--。JavaScript 把它当作单行注释,就像它对待 // 注释一样。

  4. HTML 注释结尾序列 -→ 未被 JavaScript 识别,因此它应写为 //-→。

Example

以下示例展示了如何在 JavaScript 中使用注释。

<script language = "javascript" type = "text/javascript">
   <!--
      // This is a comment. It is similar to comments in C++

      /*
      * This is a multi-line comment in JavaScript
      * It is very similar to comments in C Programming
      */
   //-->
</script>

Enabling JavaScript in Browsers

所有现代浏览器都带内置的 JavaScript 支持。通常,你可能需要手动启用或禁用此支持。本章将说明在浏览器(Internet Explorer、Firefox、chrome 和 Opera)中启用和禁用 JavaScript 支持的过程。

JavaScript in Internet Explorer

以下是打开或关闭 Internet Explorer 中的 JavaScript 的简单步骤 −

  1. 从菜单中选择 Tools → Internet Options

  2. 从对话框中选择 Security 选项卡。

  3. 单击 Custom Level 按钮。

  4. 向下滚动,直到找到 Scripting 选项。

  5. 选择 Active scripting 下的启用单选按钮。

  6. 最后,单击确定并退出

要在 Internet Explorer 中禁用 JavaScript 支持,你需要选择 Active scripting 下的 Disable 单选按钮。

JavaScript in Firefox

以下是打开或关闭 Firefox 中 JavaScript 的步骤 −

  1. 打开一个新标签页 → 在地址栏中输入 about: config

  2. 然后你将找到警告对话框。选择 I’ll be careful, I promise!

  3. 然后你将找到浏览器中的 configure options 列表。

  4. 在搜索栏中,输入 javascript.enabled

  5. 在那里,你将找到通过右键单击该选项的值来启用或禁用 JavaScript 的选项 → select toggle

如果 javascript.enabled 为真;单击 toogle 后会转换成假。如果禁用 JavaScript;单击切换后即可启用。

JavaScript in Chrome

以下是打开或关闭 Chrome 中 JavaScript 的步骤 −

  1. 单击浏览器右上角的 Chrome 菜单。

  2. Select Settings.

  3. 单击页面末尾的 Show advanced settings

  4. Privacy 部分下,单击内容设置按钮。

  5. 在“Javascript”部分,选择“不允许任何网站运行 JavaScript”或“允许所有网站运行 JavaScript(建议)”。

JavaScript in Opera

以下是打开或关闭 Opera 中 JavaScript 的步骤 −

  1. 从菜单中执行 Tools → Preferences

  2. 从对话框中选择 Advanced 选项。

  3. 从列出的项目中选择 *内容 *。

  4. Select Enable JavaScript checkbox.

  5. 最后点击“确定”并退出。

要禁用 Opera 中的 JavaScript 支持,你应该不选择 Enable JavaScript checkbox

Warning for Non-JavaScript Browsers

如果你必须使用 JavaScript 进行一些重要操作,那么可以使用 <noscript> 标记向用户显示一条警告消息。

你可以像下面那样在脚本块之后立即添加一个 noscript 块:

<html>
   <body>
      <script language = "javascript" type = "text/javascript">
         <!--
            document.write("Hello World!")
         //-->
      </script>

      <noscript>
         Sorry...JavaScript is needed to go ahead.
      </noscript>
   </body>
</html>

现在,如果用户的浏览器不支持 JavaScript 或 JavaScript 未启用,那么 </noscript> 中的信息会显示在屏幕上。

JavaScript - Placement in HTML File

允许在 HTML 文档中的任何位置包含 JavaScript 代码。然而,在 HTML 文件中包含 JavaScript 最推荐的方法如下:

  1. Script in <head>…​</head> section.

  2. Script in <body>…​</body> section.

  3. 在 <body>…​</body> 和 <head>…​</head> 部分中的脚本。

  4. 在外部文件中编写脚本,然后包含在 <head>…​</head> 部分中。

在下一节中,我们将看到如何通过不同的方式将 JavaScript 放置在 HTML 文件中。

JavaScript in <head>…​</head> section

如果你想让一个脚本在某个事件上运行,比如用户在某处单击时,那么你将像下面那样把该脚本放在头部:

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function sayHello() {
               alert("Hello World")
            }
         //-->
      </script>
   </head>

   <body>
      <input type = "button" onclick = "sayHello()" value = "Say Hello" />
   </body>
</html>

此代码将产生以下结果:

JavaScript in <body>…​</body> section

如果你需要一个脚本在页面加载时运行,以便该脚本在页面中生成内容,那么该脚本会进入文档的 <body> 部分。在这种情况下,你不会使用 JavaScript 定义任何函数。看看下面的代码。

<html>
   <head>
   </head>

   <body>
      <script type = "text/javascript">
         <!--
            document.write("Hello World")
         //-->
      </script>

      <p>This is web page body </p>
   </body>
</html>

此代码将产生以下结果:

JavaScript in <body> and <head> Sections

你可以像下面那样把 JavaScript 代码放在 <head> 和 <body> 部分:

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function sayHello() {
               alert("Hello World")
            }
         //-->
      </script>
   </head>

   <body>
      <script type = "text/javascript">
         <!--
            document.write("Hello World")
         //-->
      </script>

      <input type = "button" onclick = "sayHello()" value = "Say Hello" />
   </body>
</html>

此代码将产生以下结果 −

JavaScript in External File

当你逐渐更深入地使用 JavaScript,你会发现有些情况下你正在某个网站的多页面上重复使用相同的 JavaScript 代码。

你不一定要在多个 HTML 文件中维护相同的代码。 script 标记提供了一个机制,允许你在一个外部文件中存储 JavaScript,然后将其包含到你的 HTML 文件中。

这里有一个示例,展示了如何使用 script 标记及其 src 属性在 HTML 代码中包含一个外部 JavaScript 文件。

<html>
   <head>
      <script type = "text/javascript" src = "filename.js" ></script>
   </head>

   <body>
      .......
   </body>
</html>

要从外部文件源使用 JavaScript,你需要在扩展名为 “.js” 的简单文本文件中编写所有 JavaScript 源代码,然后像上面那样包含该文件。

例如,你可以将以下内容保存在 filename.js 文件中,然后你可以在包含 filename.js 文件后在你的 HTML 文件中使用 sayHello 函数。

function sayHello() {
   alert("Hello World")
}

JavaScript - Variables

JavaScript Datatypes

编程语言最重要的特性之一是它支持的数据类型集。这些类型的值可以在编程语言中表示和操纵。

JavaScript 允许你使用三种基本数据类型:

  1. Numbers, 例如 123、120.50 等。

  2. Strings 文本,例如“此文本字符串”等。

  3. Boolean , 例如 true 或 false。

JavaScript 也定义了两个简单的数据类型, nullundefined, ,每个只定义单个值。除开这些原始数据类型外,JavaScript 还支持称为 object 的复合数据类型。我们将在单独的章节中详细介绍对象。

Note − JavaScript 不区分整数和浮点数的值。JavaScript 中的所有数字都表示为浮点数。JavaScript 使用 IEEE 754 标准所定义的 64 位浮点格式表示数字。

JavaScript Variables

JavaScript 与许多其他编程语言类似,也有变量。可以将变量视为已命名的容器。你可以将数据放入这些容器中,然后通过命名容器来引用数据。

在 JavaScript 程序中使用变量之前,必须声明它。使用 var 关键字声明变量,如下所示:

<script type = "text/javascript">
   <!--
      var money;
      var name;
   //-->
</script>

你也可以使用相同的 var 关键字声明多个变量,如下所示:

<script type = "text/javascript">
   <!--
      var money, name;
   //-->
</script>

将值存储在变量中称为 variable initialization 。可以在创建变量时初始化变量,也可以在需要变量的稍后时间点进行初始化。

例如,你可能会创建一个名为 money 的变量,稍后为其分配 2000.50 的值。对于另一个变量,你可以在初始化时分配值,如下所示:

<script type = "text/javascript">
   <!--
      var name = "Ali";
      var money;
      money = 2000.50;
   //-->
</script>

Note − 只在文档中任何变量名的生命周期中使用 var 关键字进行声明或初始化。你不应重新声明同一个变量两次。

JavaScript 是一种 untyped 语言。这意味着 JavaScript 变量可以保存任何数据类型的值。与许多其他语言不同,你无需在变量声明期间告诉 JavaScript 变量将保存什么类型的变量。可以在程序执行期间更改变量的值类型,而 JavaScript 会自动处理它。

JavaScript Variable Scope

变量的范围是程序中定义它的区域。JavaScript 变量只有两个范围。

  1. Global Variables − 全局变量具有全局范围,这意味着它可以在 JavaScript 代码的任何位置进行定义。

  2. Local Variables − 局部变量只会在其被定义的函数中可见。函数参数始终局部于该函数。

在函数体中,局部变量优于具有相同名称的全局变量。如果使用全局变量的相同名称声明局部变量或函数参数,则可以有效隐藏全局变量。了解以下示例。

<html>
   <body onload = checkscope();>
      <script type = "text/javascript">
         <!--
            var myVar = "global";      // Declare a global variable
            function checkscope( ) {
               var myVar = "local";    // Declare a local variable
               document.write(myVar);
            }
         //-->
      </script>
   </body>
</html>

这会产生以下结果:

local

JavaScript Variable Names

在 JavaScript 中对变量命名时,请记住以下规则。

  1. 你不应该使用 JavaScript 保留关键字作为变量名。下一部分中提到了这些关键字。例如, breakboolean 变量名无效。

  2. JavaScript 变量名不应以数字(0-9)开头。它们必须以字母或下划线字符开头。例如, 123test 是无效变量名,但 _123test 是有效的变量名。

  3. JavaScript 变量名区分大小写。例如, Namename 是两个不同的变量。

JavaScript Reserved Words

下表中提供了 JavaScript 中所有保留字的列表。它们不能用作 JavaScript 变量、函数、方法、循环标签或任何对象名。

abstract

else

instanceof

switch

boolean

enum

int

synchronized

break

export

interface

this

byte

extends

long

throw

case

false

native

throws

catch

final

new

transient

char

finally

null

true

class

float

package

try

const

for

private

typeof

continue

function

protected

var

debugger

goto

public

void

default

if

return

volatile

delete

implements

short

while

do

import

static

with

double

in

super

JavaScript - Operators

What is an Operator?

我们来看一看这个简单的表达 4 + 5 is equal to 9 。这里 4 和 5 被称为 operands ,“+” 被称为 operator 。JavaScript 支持以下类型的运算符。

  1. Arithmetic Operators

  2. Comparison Operators

  3. Logical (or Relational) Operators

  4. Assignment Operators

  5. Conditional (or ternary) Operators

我们逐一了解所有运算符。

Arithmetic Operators

JavaScript 支持以下算术运算符 −

假设变量 A 为 10,变量 B 为 20,那么 −

Sr.No.

Operator & Description

1

+ (Addition) 加两个运算数 Ex: A + B 得 30

2

- (Subtraction) 从第一个运算数中减去第二个运算数 Ex: A - B 得 -10

3

* (乘法)*将两个运算数相乘 *Ex: A * B 得 200

4

/ (Division) 将分子除以分母 Ex: B / A 得 2

5

% (Modulus) 输出整数除法的余数 Ex: B % A 得 0

6

* (递增)将一个整数加 1 *Ex: A 得 11

7

-- (Decrement) 将一个整数减 1 Ex: A-- 得 9

Note − 加法运算符(+)对数字和字符串都可用。例如,"a" + 10 将得出 "a10"。

Example

以下代码演示如何在 JavaScript 中使用算术运算符。

<html>
   <body>

      <script type = "text/javascript">
         <!--
            var a = 33;
            var b = 10;
            var c = "Test";
            var linebreak = "<br />";

            document.write("a + b = ");
            result = a + b;
            document.write(result);
            document.write(linebreak);

            document.write("a - b = ");
            result = a - b;
            document.write(result);
            document.write(linebreak);

            document.write("a / b = ");
            result = a / b;
            document.write(result);
            document.write(linebreak);

            document.write("a % b = ");
            result = a % b;
            document.write(result);
            document.write(linebreak);

            document.write("a + b + c = ");
            result = a + b + c;
            document.write(result);
            document.write(linebreak);

            a = ++a;
            document.write("++a = ");
            result = ++a;
            document.write(result);
            document.write(linebreak);

            b = --b;
            document.write("--b = ");
            result = --b;
            document.write(result);
            document.write(linebreak);
         //-->
      </script>

      Set the variables to different values and then try...
   </body>
</html>

Output

a + b = 43
a - b = 23
a / b = 3.3
a % b = 3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try...

Comparison Operators

JavaScript 支持以下比较运算符 −

假设变量 A 为 10,变量 B 为 20,那么 −

Sr.No.

Operator & Description

1

= = (Equal) 如果两个运算数的值相等,则检查是否为真,如果相等,则条件变为真 Ex: (A == B) 不是真。

2

!= (Not Equal) 如果两个运算数的值不相等,则检查是否为真,如果它们不相等,则条件变为真 Ex: (A != B) 为真。

3

&gt; (Greater than) 如果左运算数的值大于右运算数的值,则检查是否为真,如果大于,则条件变为真 Ex: (A > B) 不是真。

4

&lt; (Less than) 如果左运算数的值小于右运算数的值,则检查是否为真,如果小于,则条件变为真 Ex: (A < B) 为真。

5

&gt;= (Greater than or Equal to) 如果左运算数的值大于或等于右运算数的值,则检查是否为真,如果大于或等于,则条件变为真 Ex: (A >= B) 不是真。

6

&#8656; (Less than or Equal to) 如果左运算数的值小于或等于右运算数的值,则检查是否为真,如果小于或等于,则条件变为真 Ex: (A ⇐ B) 为真。

Example

以下代码演示如何在 JavaScript 中使用比较运算符。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var a = 10;
            var b = 20;
            var linebreak = "<br />";

            document.write("(a == b) => ");
            result = (a == b);
            document.write(result);
            document.write(linebreak);

            document.write("(a < b) => ");
            result = (a < b);
            document.write(result);
            document.write(linebreak);

            document.write("(a > b) => ");
            result = (a > b);
            document.write(result);
            document.write(linebreak);

            document.write("(a != b) => ");
            result = (a != b);
            document.write(result);
            document.write(linebreak);

            document.write("(a >= b) => ");
            result = (a >= b);
            document.write(result);
            document.write(linebreak);

            document.write("(a <= b) => ");
            result = (a <= b);
            document.write(result);
            document.write(linebreak);
         //-->
      </script>
      Set the variables to different values and different operators and then try...
   </body>
</html>

Output

(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true
Set the variables to different values and different operators and then try...

Logical Operators

JavaScript 支持以下逻辑运算符:

假设变量 A 为 10,变量 B 为 20,那么 −

Sr.No.

Operator & Description

1

&amp;&amp; (Logical AND) 如果两个操作数非零,则条件变为 true。 Ex: (A && B) 为 true。

2

*

(逻辑 OR)如果两个操作数中任何一个非零,则条件变为 true。 *Ex: (A

B) is true.

3

! (Logical NOT) 反转其操作数的逻辑状态。如果条件为 true,则逻辑 NOT 运算符会将其变为 false。 Ex: ! (A && B) 为 false。

Example

尝试运行以下代码来学习如何在 JavaScript 中实现逻辑运算符。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var a = true;
            var b = false;
            var linebreak = "<br />";

            document.write("(a && b) => ");
            result = (a && b);
            document.write(result);
            document.write(linebreak);

            document.write("(a || b) => ");
            result = (a || b);
            document.write(result);
            document.write(linebreak);

            document.write("!(a && b) => ");
            result = (!(a && b));
            document.write(result);
            document.write(linebreak);
         //-->
      </script>
      <p>Set the variables to different values and different operators and then try...</p>
   </body>
</html>

Output

(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...

Bitwise Operators

JavaScript 支持以下按位运算符−

假设变量 A 的值为 2,变量 B 的值为 3,则−

Sr.No.

Operator & Description

1

&amp; (Bitwise AND) 它对整数参数的每个位执行布尔 AND 操作。 Ex: (A & B) 为 2。

2

*

(按位 OR)它对整数参数的每个位执行布尔 OR 操作。 *Ex: (A

B) is 3.

3

^ (Bitwise XOR) 它对整数参数的每个位执行布尔异或 (exclusive OR) 操作。异或意味着操作数 1 为 true 或操作数 2 为 true,但不能同时为真。 Ex: (A ^ B) 为 1。

4

~ (Bitwise Not) 它是一个一元运算符,通过反转操作数中的所有位来起作用。 Ex: (~B) 为 -4。

5

&lt;&lt; (Left Shift) 它将其第一个操作数中的所有位向左移动由第二个操作数指定的位置数。新位用零填充。将值左移一位等效于将其乘以 2,移动两位等效于乘以 4,依此类推。 Ex: (A << 1) 为 4。

6

&gt;&gt; (Right Shift) 二进制右移运算符。左操作数的值向右移动由右操作数指定的位数。 Ex: (A >> 1) 为 1。

7

&gt;&gt;&gt; (Right shift with Zero) 此运算符与 >> 运算符类似,不同之处在于左移的位始终为零。 Ex: (A >>> 1) 为 1。

Example

尝试运行以下代码在 JavaScript 中实现按位运算符。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var a = 2; // Bit presentation 10
            var b = 3; // Bit presentation 11
            var linebreak = "<br />";

            document.write("(a & b) => ");
            result = (a & b);
            document.write(result);
            document.write(linebreak);

            document.write("(a | b) => ");
            result = (a | b);
            document.write(result);
            document.write(linebreak);

            document.write("(a ^ b) => ");
            result = (a ^ b);
            document.write(result);
            document.write(linebreak);

            document.write("(~b) => ");
            result = (~b);
            document.write(result);
            document.write(linebreak);

            document.write("(a << b) => ");
            result = (a << b);
            document.write(result);
            document.write(linebreak);

            document.write("(a >> b) => ");
            result = (a >> b);
            document.write(result);
            document.write(linebreak);
         //-->
      </script>
      <p>Set the variables to different values and different operators and then try...</p>
   </body>
</html>
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different operators and then try...

Assignment Operators

JavaScript 支持以下赋值运算符 −

Sr.No.

Operator & Description

1

= (Simple Assignment ) 将右侧操作数的值赋值给左侧操作数 Ex: C = A + B 将 A + B 的值赋值给 C

2

+= (Add and Assignment) 将右侧操作数加到左侧操作数,并将结果赋值给左侧操作数。 Ex: C += A 等效于 C = C + A

3

−= (Subtract and Assignment) 将右侧操作数从左侧操作数减去,并将结果赋值给左侧操作数。 Ex: C -= A 等效于 C = C - A

4

*= (Multiply and Assignment) 将右侧操作数乘以左侧操作数,并将结果赋值给左侧操作数。 Ex: C *= A 等效于 C = C * A

5

/= (Divide and Assignment) 它将左操作数除以右操作数并把结果赋值给左操作数。 Ex: C /= A 等同于 C = C / A

6

%= (Modules and Assignment) 它使用两个操作数进行模运算并把结果赋值给左操作数。 Ex: C %= A 等同于 C = C % A

Note − 同样的逻辑适用于按位运算符,所以它们将变成 <⇐, >>=, >>=, &=, |= 和 ^=.

Example

尝试使用以下代码在 JavaScript 中实现赋值运算符。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var a = 33;
            var b = 10;
            var linebreak = "<br />";

            document.write("Value of a => (a = b) => ");
            result = (a = b);
            document.write(result);
            document.write(linebreak);

            document.write("Value of a => (a += b) => ");
            result = (a += b);
            document.write(result);
            document.write(linebreak);

            document.write("Value of a => (a -= b) => ");
            result = (a -= b);
            document.write(result);
            document.write(linebreak);

            document.write("Value of a => (a *= b) => ");
            result = (a *= b);
            document.write(result);
            document.write(linebreak);

            document.write("Value of a => (a /= b) => ");
            result = (a /= b);
            document.write(result);
            document.write(linebreak);

            document.write("Value of a => (a %= b) => ");
            result = (a %= b);
            document.write(result);
            document.write(linebreak);
         //-->
      </script>
      <p>Set the variables to different values and different operators and then try...</p>
   </body>
</html>

Output

Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...

Miscellaneous Operator

我们这里将讨论两个非常实用的 JavaScript 运算符: conditional operator (? :) 和 typeof operator .

Conditional Operator (? :)

条件运算符首先对某个表达式求值为真或假,然后根据求值的结果执行两个给定语句中的一个。

Sr.No.

Operator and Description

1

? : (Conditional ) 如果条件为真?那么值为 X:否则值为 Y

Example

尝试使用以下代码了解条件运算符在 JavaScript 中是如何工作的。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var a = 10;
            var b = 20;
            var linebreak = "<br />";

            document.write ("((a > b) ? 100 : 200) => ");
            result = (a > b) ? 100 : 200;
            document.write(result);
            document.write(linebreak);

            document.write ("((a < b) ? 100 : 200) => ");
            result = (a < b) ? 100 : 200;
            document.write(result);
            document.write(linebreak);
         //-->
      </script>
      <p>Set the variables to different values and different operators and then try...</p>
   </body>
</html>

Output

((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...

typeof Operator

typeof 运算符是一个一元运算符,它放在单个操作数之前,该操作数可以是任何类型。它的值为一个字符串,表示该操作数的数据类型。

如果操作数是数字、字符串或布尔值,typeof 运算符将求值为“number”、“string”或“boolean”,并根据求值结果返回真或假。

以下是 typeof 操作符的返回值列表。

Type

String Returned by typeof

Number

"number"

String

"string"

Boolean

"boolean"

Object

"object"

Function

"function"

Undefined

"undefined"

Null

"object"

Example

以下代码显示了如何实现 typeof 运算符。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var a = 10;
            var b = "String";
            var linebreak = "<br />";

            result = (typeof b == "string" ? "B is String" : "B is Numeric");
            document.write("Result => ");
            document.write(result);
            document.write(linebreak);

            result = (typeof a == "string" ? "A is String" : "A is Numeric");
            document.write("Result => ");
            document.write(result);
            document.write(linebreak);
         //-->
      </script>
      <p>Set the variables to different values and different operators and then try...</p>
   </body>
</html>

Output

Result => B is String
Result => A is Numeric
Set the variables to different values and different operators and then try...

JavaScript - if…​else Statement

在编写程序时,可能会出现需要采用给定路径集中某个路径的情况。在这种情况中,您需要使用条件语句,让您的程序做出正确的决策并执行正确的操作。

JavaScript 支持条件语句,用于根据不同的条件执行不同的操作。这里我们将解释 if..else 语句。

Flow Chart of if-else

以下流程图显示了 if-else 语句的工作方式。

decision making

JavaScript 支持以下形式的 if..else 语句 −

  1. if statement

  2. if…​else statement

  3. if…​else if…​ statement.

if statement

if 语句是 JavaScript 中用于做出决定和有条件执行语句的基本控制语句。

Syntax

基本 if 语句的语法如下 −

if (expression) {
   Statement(s) to be executed if expression is true
}

这里计算一个 JavaScript 表达式。如果计算结果为真,则执行给定的语句。如果该表达式为假,则不执行任何语句。在做出决策时,您大多数时候会使用比较运算符。

Example

尝试使用以下示例了解 if 语句的工作方式。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var age = 20;

            if( age > 18 ) {
               document.write("<b>Qualifies for driving</b>");
            }
         //-->
      </script>
      <p>Set the variable to different value and then try...</p>
   </body>
</html>

Output

Qualifies for driving
Set the variable to different value and then try...

if…​else statement

'if…​else' 语句是控制语句的另一种形式,允许 JavaScript 以更受控的方式执行语句。

Syntax

if (expression) {
   Statement(s) to be executed if expression is true
} else {
   Statement(s) to be executed if expression is false
}

在此,会计算 JavaScript 表达式。如果结果值为真,则将执行“if”块中的给定语句。如果表达式的值为假,则将执行 else 块中的给定语句。

Example

尝试运行以下代码,以了解如何在 JavaScript 中实现 if-else 语句。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var age = 15;

            if( age > 18 ) {
               document.write("<b>Qualifies for driving</b>");
            } else {
               document.write("<b>Does not qualify for driving</b>");
            }
         //-->
      </script>
      <p>Set the variable to different value and then try...</p>
   </body>
</html>

Output

Does not qualify for driving
Set the variable to different value and then try...

if…​else if…​ statement

if…​else if…​ 语句是 if…else 的高级形式,它允许 JavaScript 根据多个条件做出正确的决策。

Syntax

if-else-if 语句的语法如下所示:

if (expression 1) {
   Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
   Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
   Statement(s) to be executed if expression 3 is true
} else {
   Statement(s) to be executed if no expression is true
}

此代码别无特别之处。它只是一系列 if 语句,其中每个 if 都是前一条语句的 else 子句的一部分。语句基于真条件执行,如果没有条件为真,则将执行 else 块。

Example

尝试运行以下代码,以了解如何在 JavaScript 中实现 if-else-if 语句。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var book = "maths";
            if( book == "history" ) {
               document.write("<b>History Book</b>");
            } else if( book == "maths" ) {
               document.write("<b>Maths Book</b>");
            } else if( book == "economics" ) {
               document.write("<b>Economics Book</b>");
            } else {
               document.write("<b>Unknown Book</b>");
            }
         //-->
      </script>
      <p>Set the variable to different value and then try...</p>
   </body>
<html>

Output

Maths Book
Set the variable to different value and then try...

JavaScript - Switch Case

您可以使用多个 if…​else…if 语句(如上一章节中所示)执行多项分支。但这并不总是最佳解决方案,尤其是在所有分支都依赖于单个变量的值时。

从 JavaScript 1.2 开始,您可以使用 switch 语句处理这种情况,它的效率高于重复的 if…​else if 语句。

Flow Chart

下方的流程图说明了 switch-case 语句的运行方式:

switch case

Syntax

switch 语句的目标是给出一个需要计算的表达式和根据表达式的值执行的多个不同的语句。解释器会将每个 case 与表达式的值进行对比,直到找到匹配值。如果没有匹配值,则会使用 default 条件。

switch (expression) {
   case condition 1: statement(s)
   break;

   case condition 2: statement(s)
   break;
   ...

   case condition n: statement(s)
   break;

   default: statement(s)
}

break 语句表示特定 case 的结束。如果省略这些语句,解释器将继续在每个后续 case 中执行每条语句。

我们将在 Loop Control 章节中说明 break 语句。

Example

尝试执行以下示例,以实现 switch-case 语句。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var grade = 'A';
            document.write("Entering switch block<br />");
            switch (grade) {
               case 'A': document.write("Good job<br />");
               break;

               case 'B': document.write("Pretty good<br />");
               break;

               case 'C': document.write("Passed<br />");
               break;

               case 'D': document.write("Not so good<br />");
               break;

               case 'F': document.write("Failed<br />");
               break;

               default:  document.write("Unknown grade<br />")
            }
            document.write("Exiting switch block");
         //-->
      </script>
      <p>Set the variable to different value and then try...</p>
   </body>
</html>

Output

Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...

Break 语句在 switch-case 语句中发挥着主要作用。尝试运行以下代码,此代码使用了没有 break 语句的 switch-case 语句。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var grade = 'A';
            document.write("Entering switch block<br />");
            switch (grade) {
               case 'A': document.write("Good job<br />");
               case 'B': document.write("Pretty good<br />");
               case 'C': document.write("Passed<br />");
               case 'D': document.write("Not so good<br />");
               case 'F': document.write("Failed<br />");
               default: document.write("Unknown grade<br />")
            }
            document.write("Exiting switch block");
         //-->
      </script>
      <p>Set the variable to different value and then try...</p>
   </body>
</html>

Output

Entering switch block
Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block
Set the variable to different value and then try...

JavaScript - While Loops

在编写程序时,您可能会遇到需要一遍又一遍地执行某个操作的情况。在这种情况下,您需要编写循环语句,以减少代码行数。

JavaScript 支持所有必要的循环,可简化编程压力。

The while Loop

JavaScript 中最基本的循环是 while 循环,将在本章节中探讨该循环。 while 循环的目的是只要某个 expression 为真,就重复执行某条语句或代码块。一旦该表达式的值变为 false, ,循环将终止。

Flow Chart

while loop 的流程图如下所示 −

while loop

Syntax

while loop 在 JavaScript 中的语法如下所示 −

while (expression) {
   Statement(s) to be executed if expression is true
}

Example

尝试运行以下示例,以实现 while 循环。

<html>
   <body>

      <script type = "text/javascript">
         <!--
            var count = 0;
            document.write("Starting Loop ");

            while (count < 10) {
               document.write("Current Count : " + count + "<br />");
               count++;
            }

            document.write("Loop stopped!");
         //-->
      </script>

      <p>Set the variable to different value and then try...</p>
   </body>
</html>

Output

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...

The do…​while Loop

do…​while 循环与 while 循环类似,区别在于条件检查发生在循环结尾。这意味着循环将始终至少执行一次,即使条件为 false

Flow Chart

do-while 循环的流程图如下 −

do while loop

Syntax

JavaScript 中 do-while 循环的语法如下 −

do {
   Statement(s) to be executed;
} while (expression);

Note - 不要错过 do…​while 循环结尾处所用的分号。

Example

通过以下示例来学习如何在 JavaScript 中实现一个 do-while 循环。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var count = 0;

            document.write("Starting Loop" + "<br />");
            do {
               document.write("Current Count : " + count + "<br />");
               count++;
            }

            while (count < 5);
            document.write ("Loop stopped!");
         //-->
      </script>
      <p>Set the variable to different value and then try...</p>
   </body>
</html>

Output

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!
Set the variable to different value and then try...

JavaScript - For Loop

for 循环是最紧凑的循环形式。它包括以下三个重要部分 -

  1. 我们初始化计数器为一个起始值,即 loop initialization 。初始化语句在循环开始前执行。

  2. test statement 将测试给定条件为真或假。如果条件为真,则在循环内给定的代码将被执行,否则控件将退出循环。

  3. iteration statement 可以增加或减小计数器。

你可以用分号分隔三个部分,把它们放在一行中。

Flow Chart

for 循环在 JavaScript 中的流程图如下 −

for loop

Syntax

for 循环在 JavaScript 中的语法如下 −

for (initialization; test condition; iteration statement) {
   Statement(s) to be executed if test condition is true
}

Example

通过以下示例来了解 for 循环在 JavaScript 中的工作原理。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var count;
            document.write("Starting Loop" + "<br />");

            for(count = 0; count < 10; count++) {
               document.write("Current Count : " + count );
               document.write("<br />");
            }
            document.write("Loop stopped!");
         //-->
      </script>
      <p>Set the variable to different value and then try...</p>
   </body>
</html>

Output

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...

JavaScript for…​in loop

for…​in 循环用于循环遍历对象的属性。因为我们还没有讨论过对象,所以你可能对此循环感到不适应。但一旦你理解 JavaScript 中对象的运行方式,你将发现这个循环很有用。

Syntax

for (variablename in object) {
   statement or block to execute
}

在每次迭代中, object 中的一个属性被分配给 variablename ,此循环将持续到对象的全部属性都被穷尽。

Example

通过以下示例来实现“for-in”循环。它打印 web 浏览器的 Navigator 对象。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var aProperty;
            document.write("Navigator Object Properties<br /> ");
            for (aProperty in navigator) {
               document.write(aProperty);
               document.write("<br />");
            }
            document.write ("Exiting from the loop!");
         //-->
      </script>
      <p>Set the variable to different object and then try...</p>
   </body>
</html>

Output

Navigator Object Properties
serviceWorker
webkitPersistentStorage
webkitTemporaryStorage
geolocation
doNotTrack
onLine
languages
language
userAgent
product
platform
appVersion
appName
appCodeName
hardwareConcurrency
maxTouchPoints
vendorSub
vendor
productSub
cookieEnabled
mimeTypes
plugins
javaEnabled
getStorageUpdates
getGamepads
webkitGetUserMedia
vibrate
getBattery
sendBeacon
registerProtocolHandler
unregisterProtocolHandler
Exiting from the loop!
Set the variable to different object and then try...

JavaScript - Loop Control

JavaScript提供对循环和switch语句的完全控制。在某些情况下,您可能需要退出循环而不到达其底部。另外,您可能需要跳过代码块的一部分并开始循环的下一次迭代。

为了处理所有此类情况,JavaScript 提供了 breakcontinue 语句。这些语句分别用于立即退出任何循环或开始任何循环的下一个迭代。

The break Statement

break 语句与 switch 语句一起被简要介绍过,用于提前退出循环,从封闭的花括号中跳出。

Flow Chart

break语句的流程图如下所示 −

break statement

Example

以下示例说明了使用 break 语句与 while 循环。注意循环如何一到达 5 就提前退出,并且到达作为结束花括号下方 document.write (..) 语句 -

<html>
   <body>
      <script type = "text/javascript">
         <!--
         var x = 1;
         document.write("Entering the loop<br /> ");

         while (x < 20) {
            if (x == 5) {
               break;   // breaks out of loop completely
            }
            x = x + 1;
            document.write( x + "<br />");
         }
         document.write("Exiting the loop!<br /> ");
         //-->
      </script>

      <p>Set the variable to different value and then try...</p>
   </body>
</html>

Output

Entering the loop
2
3
4
5
Exiting the loop!
Set the variable to different value and then try...

我们已经看到 break 语句在 a switch 语句中的用法。

The continue Statement

continue 语句告诉解释器立即开始循环的下一个迭代并跳过剩余的代码块。当遇到 continue 语句时,程序流程立即移动到循环检查表达式,如果条件仍然为真,则它开始下一个迭代,否则控件将退出循环。

Example

此示例说明了将 continue 语句与while循环一起使用的情况。注意,当 x 变量中持有的索引达到5时,如何使用 continue 语句跳过打印 −

<html>
   <body>
      <script type = "text/javascript">
         <!--
            var x = 1;
            document.write("Entering the loop<br /> ");

            while (x < 10) {
               x = x + 1;

               if (x == 5) {
                  continue;   // skip rest of the loop body
               }
               document.write( x + "<br />");
            }
            document.write("Exiting the loop!<br /> ");
         //-->
      </script>
      <p>Set the variable to different value and then try...</p>
   </body>
</html>

Output

Entering the loop
2
3
4
6
7
8
9
10
Exiting the loop!
Set the variable to different value and then try...

Using Labels to Control the Flow

从JavaScript 1.2开始,可以使用标签和 breakcontinue 来更精确地控制流。 label 只是表示符,后跟冒号(:),可以用到语句或代码块中。我们将看到两个不同的示例以理解如何将标签与break和continue结合使用。

Note - 不允许在 ‘continue’‘break’ 语句及其标签名之间换行。而且,标签名和关联循环之间也不应该有任何其他语句。

尝试以下两个示例以更好地理解标签。

Example 1

以下示例演示如何使用 break 语句实现标签。

<html>
   <body>
      <script type = "text/javascript">
         <!--
            document.write("Entering the loop!<br /> ");
            outerloop:        // This is the label name
            for (var i = 0; i < 5; i++) {
               document.write("Outerloop: " + i + "<br />");
               innerloop:
               for (var j = 0; j < 5; j++) {
                  if (j > 3 ) break ;           // Quit the innermost loop
                  if (i == 2) break innerloop;  // Do the same thing
                  if (i == 4) break outerloop;  // Quit the outer loop
                  document.write("Innerloop: " + j + " <br />");
               }
            }
            document.write("Exiting the loop!<br /> ");
         //-->
      </script>
   </body>
</html>

Output

Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 2
Outerloop: 3
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 4
Exiting the loop!

Example 2

<html>
   <body>

      <script type = "text/javascript">
         <!--
         document.write("Entering the loop!<br /> ");
         outerloop:     // This is the label name

         for (var i = 0; i < 3; i++) {
            document.write("Outerloop: " + i + "<br />");
            for (var j = 0; j < 5; j++) {
               if (j == 3) {
                  continue outerloop;
               }
               document.write("Innerloop: " + j + "<br />");
            }
         }

         document.write("Exiting the loop!<br /> ");
         //-->
      </script>

   </body>
</html>

Output

Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
Exiting the loop!

JavaScript - Functions

函数是一组可重用代码,可以在程序中的任何地方调用它。这就消除了反复编写相同代码的需要。它帮助程序员编写模块化代码。函数允许程序员将一个大型程序划分为一些小而易于管理的函数。

与其他高级编程语言一样,JavaScript 也支持使用函数编写模块化代码所需的一切功能。你一定在前面的章节中看到过 alert()write() 这样的函数。我们一直在反复使用这些函数,但是它们只在核心 JavaScript 中被编写过一次。

JavaScript 也允许我们编写自己的函数。本节介绍如何在 JavaScript 中编写自己的函数。

Function Definition

在使用函数之前,我们需要定义它。在 JavaScript 中定义函数最常见的方式是使用 function 关键字,后面跟一个唯一函数名、一个可能为空的参数列表以及花括号括起来的一个语句块。

Syntax

以下显示基础语法。

<script type = "text/javascript">
   <!--
      function functionname(parameter-list) {
         statements
      }
   //-->
</script>

Example

尝试以下示例。它定义了一个名为 sayHello 的函数,该函数不使用参数 -

<script type = "text/javascript">
   <!--
      function sayHello() {
         alert("Hello there");
      }
   //-->
</script>

Calling a Function

要在脚本中稍后的某个地方调用某个函数,您只需按照以下代码所示编写该函数的名称。

<html>
   <head>
      <script type = "text/javascript">
         function sayHello() {
            document.write ("Hello there!");
         }
      </script>

   </head>

   <body>
      <p>Click the following button to call the function</p>
      <form>
         <input type = "button" onclick = "sayHello()" value = "Say Hello">
      </form>
      <p>Use different text in write method and then try...</p>
   </body>
</html>

Output

Function Parameters

到目前为止,我们已经看到了没有参数的函数。但在调用函数时,可以使用一个功能来传递不同参数。这些已传递参数可以在函数中捕获,并且可以对这些参数执行任何操作。函数可以接受多个以逗号分隔的参数。

Example

尝试以下示例。我们在这里修改了我们的 sayHello 函数。现在,它使用两个参数。

<html>
   <head>
      <script type = "text/javascript">
         function sayHello(name, age) {
            document.write (name + " is " + age + " years old.");
         }
      </script>
   </head>

   <body>
      <p>Click the following button to call the function</p>
      <form>
         <input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
      </form>
      <p>Use different parameters inside the function and then try...</p>
   </body>
</html>

Output

The return Statement

JavaScript 函数可以具有可选的 return 语句。如果您想从函数中返回值,则需要此语句。此语句应该是函数中的最后一个语句。

例如,您可以在函数中传递两个数字,然后让该函数在您的调用程序中返回它们的乘积。

Example

尝试以下示例。它定义了一个函数,该函数采用两个参数,并在将结果返回调用程序中之前将它们连接起来。

<html>
   <head>
      <script type = "text/javascript">
         function concatenate(first, last) {
            var full;
            full = first + last;
            return full;
         }
         function secondFunction() {
            var result;
            result = concatenate('Zara', 'Ali');
            document.write (result );
         }
      </script>
   </head>

   <body>
      <p>Click the following button to call the function</p>
      <form>
         <input type = "button" onclick = "secondFunction()" value = "Call Function">
      </form>
      <p>Use different parameters inside the function and then try...</p>
  </body>
</html>

Output

JavaScript 函数还有很多需要了解的地方,然而我们已经在这篇教程中涵盖了最重要的概念。

JavaScript - Events

What is an Event ?

JavaScript 与 HTML 的交互是通过用户或浏览器操作页面时发生的事件进行处理的。

当页面加载时,这被称为一个事件。当用户单击一个按钮时,该单击也是一个事件。其他示例包括诸如按任意键、关闭窗口、调整窗口大小等事件。

开发者可以使用这些事件来执行 JavaScript 编码响应,这会导致按钮关闭窗口、向用户显示消息、验证数据以及几乎任何其他类型的可想而知响应。

事件是文档对象模型 (DOM) 级别 3 的一部分,每个 HTML 元素都包含一组可以触发 JavaScript 代码的事件。

请浏览这个小程序教程以更好地理解 HTML Event Reference 。在这里,我们将看到几个示例来理解事件和 JavaScript 之间的关系 -

onclick Event Type

这是用户单击其鼠标左键时发生的最常用事件类型。您可以针对此事件类型放置您的验证、警告等操作。

Example

尝试以下示例。

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function sayHello() {
               alert("Hello World")
            }
         //-->
      </script>
   </head>

   <body>
      <p>Click the following button and see result</p>
      <form>
         <input type = "button" onclick = "sayHello()" value = "Say Hello" />
      </form>
   </body>
</html>

Output

onsubmit Event Type

onsubmit 是您尝试提交表单时发生的事件。您可以针对此事件类型放置您的表单验证。

Example

以下示例显示了如何使用 onsubmit。我们在此准备向 web 服务器提交表单数据之前调用一个 validate() 函数。如果 validate() 函数返回 true,则表单将被提交,否则它将不提交数据。

尝试以下示例。

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function validation() {
               all validation goes here
               .........
               return either true or false
            }
         //-->
      </script>
   </head>

   <body>
      <form method = "POST" action = "t.cgi" onsubmit = "return validate()">
         .......
         <input type = "submit" value = "Submit" />
      </form>
   </body>
</html>

onmouseover and onmouseout

这两种事件类型将帮助您使用图像甚至文本创建不错的效果。 onmouseover 事件在您将鼠标悬停在任意元素上面时触发, onmouseout 在您将鼠标移出该元素时触发。尝试以下示例。

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function over() {
               document.write ("Mouse Over");
            }
            function out() {
               document.write ("Mouse Out");
            }
         //-->
      </script>
   </head>

   <body>
      <p>Bring your mouse inside the division to see the result:</p>
      <div onmouseover = "over()" onmouseout = "out()">
         <h2> This is inside the division </h2>
      </div>
   </body>
</html>

Output

HTML 5 Standard Events

在此处列出标准的 HTML 5 事件以供您参考。此处脚本指示针对该事件执行的 Javascript 函数。

Attribute

Value

Description

Offline

script

当文档脱机时触发

Onabort

script

在中止事件上触发

onafterprint

script

在文档打印后触发

onbeforeonload

script

在文档加载之前触发

onbeforeprint

script

在文档打印之前触发

onblur

script

当窗口失去焦点时触发

oncanplay

script

当媒体可以开始播放,但可能由于缓冲而停止时触发

oncanplaythrough

script

当媒体可以一直播放到结尾,而不用因为缓冲而停止时触发

onchange

script

当元素发生变化时触发

onclick

script

在鼠标单击上触发

oncontextmenu

script

当触发上下文菜单时触发

ondblclick

script

在鼠标双击上触发

ondrag

script

当元素被拖动时触发

ondragend

script

在拖动操作结束时触发

ondragenter

script

当元素已经拖动到有效的放置目标时触发

ondragleave

script

当元素被拖动到有效的放置目标上时触发

ondragover

script

在拖动操作开始时触发

ondragstart

script

在拖动操作开始时触发

ondrop

script

当被拖动的元素被放置时触发

ondurationchange

script

当媒体长度发生变化时触发

onemptied

script

当媒体资源元素突然变为空时触发。

onended

script

当媒体到达末尾时触发。

onerror

script

当发生错误时触发。

onfocus

script

当窗口获得焦点时触发。

onformchange

script

当表单更改时触发。

onforminput

script

当表单获得用户输入时触发。

onhaschange

script

当文档已更改时触发。

oninput

script

当元素获得用户输入时触发。

oninvalid

script

当元素无效时触发。

onkeydown

script

当按下某个键时触发。

onkeypress

script

当按下并释放某个键时触发。

onkeyup

script

当释放某个键时触发。

onload

script

当文档加载时触发。

onloadeddata

script

当媒体数据加载时触发。

onloadedmetadata

script

当媒体元素的持续时间和其他媒体数据加载时触发。

onloadstart

script

当浏览器开始加载媒体数据时触发。

onmessage

script

当触发消息时触发。

onmousedown

script

当按下鼠标按钮时触发。

onmousemove

script

当鼠标指针移动时触发。

onmouseout

script

当鼠标指针移出元素时触发

onmouseover

script

当鼠标指针移入元素时触发

onmouseup

script

当释放鼠标按钮时触发

onmousewheel

script

当旋转鼠标滚轮时触发

onoffline

script

当文档脱机时触发

onoine

script

当文档联机时触发

ononline

script

当文档联机时触发

onpagehide

script

当窗口隐藏时触发

onpageshow

script

当窗口可见时触发

onpause

script

当暂停媒体数据时触发

onplay

script

当媒体数据开始播放时触发

onplaying

script

当媒体数据开始播放时触发

onpopstate

script

当窗口的历史记录发生变化时触发

onprogress

script

当浏览器正在获取媒体数据时触发

onratechange

script

当媒体数据的播放速度发生变化时触发

onreadystatechange

script

当就绪状态发生变化时触发

onredo

script

当文档执行重做操作时触发

onresize

script

当窗口调整大小时触发

onscroll

script

当滚动元素的滚动条时触发

onseeked

script

当媒体元素的 seeking 属性不再为 true 且 seeking 已经结束时触发

onseeking

script

当媒体元素的 seeking 属性为 true 且 seeking 已经开始时触发

onselect

script

在元素被选择时触发

onstalled

script

在获取媒体数据时出错时触发

onstorage

script

当文件加载时触发

onsubmit

script

在表单提交时触发

onsuspend

script

当浏览器正在获取媒体数据但没有获取到整个媒体文件时触发

ontimeupdate

script

当媒体改变播放位置时触发

onundo

script

当文档执行撤消操作时触发

onunload

script

当用户离开文档时触发

onvolumechange

script

当媒体改变音量时触发,包括设置“静音”

onwaiting

script

当媒体停止播放但预计会继续时触发

JavaScript and Cookies

What are Cookies ?

Web 浏览器和服务器使用 HTTP 协议进行通信,而 HTTP 是一个无状态协议。但是,对于商业网站而言,需要在不同页面之间维护会话信息。例如,用户完成多个页面的操作后结束注册。但是,如何在所有网页中维护用户会话信息。

在许多情况下,使用 cookie 是记忆和跟踪偏好、购买、佣金和其他信息最有效的方法,而这些信息对于提升访问者体验或网站统计至关重要。

How It Works ?

您的服务器以 cookie 的形式向访问者的浏览器发送部分数据。浏览器可能会接收该 cookie。如果接受,它会以纯文本记录的形式存储在访问者的硬盘上。现在,当访问者访问您网站上的另一个页面时,浏览器会向服务器发送相同的 cookie 以供检索。检索后,您的服务器会知道/记住之前存储的内容。

Cookie 是纯文本数据记录,包含 5 个可变长度字段:

  1. Expires − cookie 的过期日期。如果留空,则 cookie 将在访问者退出浏览器时过期。

  2. Domain − 您网站的域名。

  3. Path − 设置 cookie 的目录或网页的路径。如果您希望从任何目录或页面检索 cookie,则可以留空。

  4. Secure − 如果此字段包含单词“安全”,那么只能使用安全服务器检索 cookie。如果此字段留空,则不存在此类限制。

  5. Name=Value − cookie 以键值对的形式设置和检索

Cookie 的最初设计是为了 CGI 编程。Cookie 中包含的数据会自动在 Web 浏览器和 Web 服务器之间传输,这样服务器上的 CGI 脚本就能读取和写入存储在客户端上的 Cookie 值。

JavaScript 也可以使用 Document 对象的 cookie 属性来操作 Cookie。JavaScript 能读取、创建、修改和删除适用于当前网页的 Cookie。

Storing Cookies

创建 Cookie 的最简单的方法是将一个字符串值分配给 document.cookie 对象,如下所示。

document.cookie = "key1 = value1;key2 = value2;expires = date";

这里的 expires 属性是可选的。如果您使用有效日期或时间提供这个属性,则 Cookie 将在给定的日期或时间过期,此后无法再访问 Cookie 的值。

Note - Cookie 值不能包含分号、逗号或空格。由于此原因,您可能希望在将 JavaScript escape() 函数编码后存储在 Cookie 中之前使用该函数。如果您这么做,在读取 Cookie 值时,您还必须使用相应的 unescape() 函数。

Example

尝试以下操作。它在输入 Cookie 中设置一个客户名称。

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function WriteCookie() {
               if( document.myform.customer.value == "" ) {
                  alert("Enter some value!");
                  return;
               }
               cookievalue = escape(document.myform.customer.value) + ";";
               document.cookie = "name=" + cookievalue;
               document.write ("Setting Cookies : " + "name=" + cookievalue );
            }
         //-->
      </script>
   </head>

   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
      </form>
   </body>
</html>

Output

现在,您的计算机有一个名为 name 的 Cookie。您可以使用多个以逗号分隔的键值对来设置多个 Cookie。

Reading Cookies

读取 Cookie 和编写 Cookie 同样简单,因为 document.cookie 对象的值就是 Cookie。因此,每次您要访问 Cookie 时,都可以使用这个字符串。document.cookie 字符串将保留一个由分号分隔的名值对列表,其中 name 是 Cookie 的名称,value 是它的字符串值。

您可以使用字符串的 split() 函数将字符串分解为键和值,如下所示 -

Example

尝试以下示例以获取所有 Cookie。

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function ReadCookie() {
               var allcookies = document.cookie;
               document.write ("All Cookies : " + allcookies );

               // Get all the cookies pairs in an array
               cookiearray = allcookies.split(';');

               // Now take key value pair out of this array
               for(var i=0; i<cookiearray.length; i++) {
                  name = cookiearray[i].split('=')[0];
                  value = cookiearray[i].split('=')[1];
                  document.write ("Key is : " + name + " and Value is : " + value);
               }
            }
         //-->
      </script>
   </head>

   <body>
      <form name = "myform" action = "">
         <p> click the following button and see the result:</p>
         <input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
      </form>
   </body>
</html>

Note - 这里 lengthArray 类的某个方法,它返回数组的长度。我们在单独章节中讨论数组。在讨论之前,请尝试理解一下。

Note - 您的计算机中可能已经设置了其他一些 Cookie。以上代码将显示计算机中设置的所有 Cookie。

Setting Cookies Expiry Date

您可以通过设置一个过期日期并在 Cookie 中保存过期日期来将 Cookie 的生存期延长到当前浏览器会话之后。这可以通过设置 ‘expires’ 属性为一个日期和时间来实现。

Example

尝试以下示例。它说明如何将 Cookie 的过期日期延长 1 个月。

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function WriteCookie() {
               var now = new Date();
               now.setMonth( now.getMonth() + 1 );
               cookievalue = escape(document.myform.customer.value) + ";"

               document.cookie = "name=" + cookievalue;
               document.cookie = "expires=" + now.toUTCString() + ";"
               document.write ("Setting Cookies : " + "name=" + cookievalue );
            }
         //-->
      </script>
   </head>

   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>
   </body>
</html>

Output

有时,您会希望删除一个 Cookie,以便后续尝试读取 Cookie 时没有任何返回结果。要做到这一点,您只需要将过期日期设置为过去的时间。

Example

尝试以下示例。它说明如何通过将过期日期设置为当前日期之前的一个月来删除 Cookie。

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function WriteCookie() {
               var now = new Date();
               now.setMonth( now.getMonth() - 1 );
               cookievalue = escape(document.myform.customer.value) + ";"

               document.cookie = "name=" + cookievalue;
               document.cookie = "expires=" + now.toUTCString() + ";"
               document.write("Setting Cookies : " + "name=" + cookievalue );
            }
          //-->
      </script>
   </head>

   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>
   </body>
</html>

Output

JavaScript - Page Redirection

What is Page Redirection ?

您可能遇到过如下情况,点击了一个 URL 以访问页面 X,但您在内部被导向了另一个页面 Y。这种情况是 page redirection 导致的。这个概念不同于 JavaScript Page Refresh

您希望将用户从原始页面重定向的原因可能有多种。我们列出了其中一些原因 -

  1. 您不喜欢自己域的名称,并且您要移动到一个新名称。在这种情况下,您可能希望将所有访问者都定向到新网站。您可以保留旧域,但放置一个带重定向页面的页面,这样旧域的所有访问者都可以访问您的新域。

  2. 你根据浏览器版本或名称或不同国家建立了不同的页面,然后你可以使用客户端页面重定向将用户转到适当的页面,而不是使用服务器端页面重定向。

  3. 搜索引擎可能已编入你的页面索引。但在移到另一个域时,你肯定不希望失去通过搜索引擎访问你网站的访问者。因此,你可以使用客户端页面重定向。但请记住,不要使用此方法来愚弄搜索引擎,这样做可能会导致你的网站被屏蔽。

How Page Re-direction Works ?

页面重定向的实现如下。

Example 1

使用客户端的 JavaScript 进行页面重定向非常简单。要将网站访问者重定向到一个新页面,你只需在头部分中添加一个如下所示的行。

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function Redirect() {
               window.location = "https://www.tutorialspoint.com";
            }
         //-->
      </script>
   </head>

   <body>
      <p>Click the following button, you will be redirected to home page.</p>

      <form>
         <input type = "button" value = "Redirect Me" onclick = "Redirect();" />
      </form>

   </body>
</html>

Output

Example 2

在将网站访问者重定向到一个新页面之前,你可以向他们显示适当的信息。这需要一点时间来加载一个新页面。下面的示例展示了如何实现该方法。其中 setTimeout() 是一个内置 JavaScript 函数, 可用于在给定时间间隔后执行另一个函数。

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function Redirect() {
               window.location = "https://www.tutorialspoint.com";
            }
            document.write("You will be redirected to main page in 10 sec.");
            setTimeout('Redirect()', 10000);
         //-->
      </script>
   </head>

   <body>
   </body>
</html>

Output

You will be redirected to tutorialspoint.com main page in 10 seconds!

Example 3

下面的示例展示了如何根据浏览器将网站访问者重定向到一个不同的页面。

<html>
   <head>
      <script type = "text/javascript">
         <!--
            var browsername = navigator.appName;
            if( browsername == "Netscape" ) {
               window.location = "http://www.location.com/ns.htm";
            } else if ( browsername =="Microsoft Internet Explorer") {
               window.location = "http://www.location.com/ie.htm";
            } else {
               window.location = "http://www.location.com/other.htm";
            }
         //-->
      </script>
   </head>

   <body>
   </body>
</html>

JavaScript - Dialog Boxes

JavaScript 支持三种重要的对话框类型。这些对话框可用于发出警告或确认任何输入,或获取用户的一种输入。这里我们将一一讨论每个对话框。

Alert Dialog Box

警报对话框主要用于向用户发出警告信息。例如,如果一个输入字段需要输入文本,但用户未提供任何输入,那么作为验证的一部分,你可以使用一个警报框来发出警告信息。

此外,警报框可用于更友好的信息。警报框仅提供一个按钮“确定”供用户选择并继续。

Example

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function Warn() {
               alert ("This is a warning message!");
               document.write ("This is a warning message!");
            }
         //-->
      </script>
   </head>

   <body>
      <p>Click the following button to see the result: </p>
      <form>
         <input type = "button" value = "Click Me" onclick = "Warn();" />
      </form>
   </body>
</html>

Output

Confirmation Dialog Box

确认对话框主要用于获取用户的同意选项。它显示一个带有两个按钮的对话框: OKCancel

如果用户单击确定按钮,则窗口方法 confirm() 将返回 true。如果用户单击取消按钮,则 confirm() 将返回 false。你可以如下使用确认对话框。

Example

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function getConfirmation() {
               var retVal = confirm("Do you want to continue ?");
               if( retVal == true ) {
                  document.write ("User wants to continue!");
                  return true;
               } else {
                  document.write ("User does not want to continue!");
                  return false;
               }
            }
         //-->
      </script>
   </head>

   <body>
      <p>Click the following button to see the result: </p>
      <form>
         <input type = "button" value = "Click Me" onclick = "getConfirmation();" />
      </form>
   </body>
</html>

Output

Prompt Dialog Box

当你想要弹出文本框以获取用户输入时,提示对话框非常有用。因此,它使你能够与用户进行交互。用户需要填写该字段,然后单击确定。

使用一个名为 prompt() 的方法显示此对话框,该方法采用两个参数:(i) 想在文本框中显示的标签和 (ii) 想在文本框中显示的默认字符串。

此对话框有两个按钮: OKCancel 。如果用户单击确定按钮,则窗口方法 prompt() 将返回从文本框输入的值。如果用户单击取消按钮,则窗口方法 prompt() 将返回 null

Example

以下示例展示如何使用提示对话框 −

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function getValue() {
               var retVal = prompt("Enter your name : ", "your name here");
               document.write("You have entered : " + retVal);
            }
         //-->
      </script>
   </head>

   <body>
      <p>Click the following button to see the result: </p>
      <form>
         <input type = "button" value = "Click Me" onclick = "getValue();" />
      </form>
   </body>
</html>

Output

JavaScript - Void Keyword

void 是 JavaScript 中的一个重要关键字,可作为一元运算符使用,它出现在其单个操作数之前,该操作数可以是任何类型。此运算符指定要计算而不返回值的表达式。

Syntax

void 的语法可以是以下两种之一 −

<head>
   <script type = "text/javascript">
      <!--
         void func()
         javascript:void func()
         or:
         void(func())
         javascript:void(func())
      //-->
   </script>
</head>

Example 1

此运算符最常见的用途是在客户端 javascript:URL 中,它允许你计算表达式的副作用,而无需浏览器显示计算表达式 的值。

这里对表达式 alert ('Warning!!!') 进行了计算,但不会将其加载回当前文档中 −

<html>
   <head>
      <script type = "text/javascript">
         <!--
         //-->
      </script>
   </head>

   <body>
      <p>Click the following, This won't react at all...</p>
      <a href = "javascript:void(alert('Warning!!!'))">Click me!</a>
   </body>
</html>

Output

Example 2

仔细查看下面的示例。下面的链接没有任何作用,因为 JavaScript 中的表达式“0”没有效果。在这里,“0”表达式被求值,但它不会被重新加载到当前文档中。

<html>
   <head>
      <script type = "text/javascript">
         <!--
         //-->
      </script>
   </head>

   <body>
      <p>Click the following, This won't react at all...</p>
      <a href = "javascript:void(0)">Click me!</a>
   </body>
</html>

Output

Example 3

void 的另一个使用是用它执行如下动作,来特意生成 undefined 值。

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function getValue() {
               var a,b,c;

               a = void ( b = 5, c = 7 );
               document.write('a = ' + a + ' b = ' + b +' c = ' + c );
            }
         //-->
      </script>
   </head>

   <body>
      <p>Click the following to see the result:</p>
      <form>
         <input type = "button" value = "Click Me" onclick = "getValue();" />
      </form>
   </body>
</html>

Output

JavaScript - Page Printing

很多时候,希望在你的网页中放置一个按钮,以此通过实际打印机打印该网页的内容。JavaScript 帮助你使用 window 对象的 print 函数来实现这一功能。

JavaScript print 函数 window.print() 在执行时会打印当前网页。你可以直接使用 onclick 事件来调用此函数,如下面的示例所示。

Example

尝试以下示例。

<html>
   <head>
      <script type = "text/javascript">
         <!--
         //-->
      </script>
   </head>

   <body>
      <form>
         <input type = "button" value = "Print" onclick = "window.print()" />
      </form>
   </body>
<html>

Output

尽管它对获取打印输出有帮助,但它并不是一种推荐的方法。对于打印机来说,友好页面其实就是没有图像、图形或广告副本的页面。

你可以通过以下方法让网页成为打印机友好型页面:

  1. 制作该页面的副本,把不想要的内容和图像留出,然后从原始页面链接到打印机友好型页面。查看 Example

  2. 如果你不想保留页面的额外副本,那么你可以使用正确的注释把要打印的文本标记出来,比如 <!-- PRINT STARTS HERE -→…​.. <!-- PRINT ENDS HERE -→ ,然后在后台使用 PERL 或任何其他脚本清除可打印文本并显示最终的打印内容。我们 Tutorialspoint 使用此方法为我们的网站访问者提供打印功能。

How to Print a Page?

如果你没有在网页上找到上述功能,那么你可以使用浏览器的标准工具栏来打印网页。请按照下列链接进行操作。

File →  Print → Click OK  button.

JavaScript - Objects Overview

JavaScript 是一种面向对象编程 (OOP) 语言。如果编程语言为开发人员提供了以下四种基本功能,则该编程语言可以被称为面向对象编程语言:

  1. Encapsulation − 将相关信息,不管是数据还是方法,一起存储到一个对象中的功能。

  2. Aggregation − 将一个对象存储到另一个对象中的功能。

  3. Inheritance − 让一个类依赖于另一个类(或多个类)获得其一些属性和方法的功能。

  4. Polymorphism − 编写一个函数或方法,以各种不同的方式运行的功能。

对象由属性组成。如果属性包含一个函数,那么它会被视为对象的一种方法,否则该属性会被视为一种属性。

Object Properties

对象属性可以是三种基本数据类型中的任何一种,或任何抽象数据类型,例如另一个对象。对象属性通常是在对象的函数中内部使用的变量,但它也可以是贯穿整个页面使用的全局变量。

向对象添加属性的语法为:

objectName.objectProperty = propertyValue;

For example − 以下代码使用 document 对象的 "title" 属性获取文档标题。

var str = document.title;

Object Methods

方法是让对象做某事或让某些事对对象执行的函数。函数与方法之间存在小差异 - 函数是一个独立的语句单元,而方法依附于对象,并且可以由 this 关键字引用。

这些方法对从显示对象内容到屏幕到对一组局部属性和参数执行复杂数学运算的所有内容都很有用。

For example - 以下是一个简单的示例,展示如何使用文档对象的 write() 方法写入文档中任何内容。

document.write("This is test");

User-Defined Objects

所有用户定义的对象和内置的对象都是称为 Object 的对象的子项。

The new Operator

new 运算符用于创建对象的实例。要创建对象, new 运算符后跟构造方法。

在以下示例中,构造方法为 Object()、Array() 和 Date()。这些构造函数是内置的 JavaScript 函数。

var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");

The Object() Constructor

构造函数是一个用于创建和初始化对象的功能。JavaScript 提供了一个名为 Object() 的特殊构造函数来构建对象。 Object() 构造函数的返回值被分配给一个变量。

该变量包含对新对象的引用。分配给对象的属性不是变量,并且没有使用 var 关键字定义。

Example 1

尝试以下示例;它演示如何创建对象。

<html>
   <head>
      <title>User-defined objects</title>
      <script type = "text/javascript">
         var book = new Object();   // Create the object
         book.subject = "Perl";     // Assign properties to the object
         book.author  = "Mohtashim";
      </script>
   </head>

   <body>
      <script type = "text/javascript">
         document.write("Book name is : " + book.subject + "<br>");
         document.write("Book author is : " + book.author + "<br>");
      </script>
   </body>
</html>

Output

Book name is : Perl
Book author is : Mohtashim

Example 2

此示例演示如何使用用户定义函数创建对象。在这里, this 关键字用于引用已传递给函数的对象。

<html>
   <head>
   <title>User-defined objects</title>
      <script type = "text/javascript">
         function book(title, author) {
            this.title = title;
            this.author  = author;
         }
      </script>
   </head>

   <body>
      <script type = "text/javascript">
         var myBook = new book("Perl", "Mohtashim");
         document.write("Book title is : " + myBook.title + "<br>");
         document.write("Book author is : " + myBook.author + "<br>");
      </script>
   </body>
</html>

Output

Book title is : Perl
Book author is : Mohtashim

Defining Methods for an Object

前面的示例演示了构造函数如何创建对象并分配属性。但是我们需要通过向其分配方法来完成对对象的定义。

Example

尝试以下示例;它显示如何将一个函数与一个对象一起添加。

<html>

   <head>
   <title>User-defined objects</title>
      <script type = "text/javascript">
         // Define a function which will work as a method
         function addPrice(amount) {
            this.price = amount;
         }

         function book(title, author) {
            this.title = title;
            this.author  = author;
            this.addPrice = addPrice;  // Assign that method as property.
         }
      </script>
   </head>

   <body>
      <script type = "text/javascript">
         var myBook = new book("Perl", "Mohtashim");
         myBook.addPrice(100);

         document.write("Book title is : " + myBook.title + "<br>");
         document.write("Book author is : " + myBook.author + "<br>");
         document.write("Book price is : " + myBook.price + "<br>");
      </script>
   </body>
</html>

Output

Book title is : Perl
Book author is : Mohtashim
Book price is : 100

The 'with' Keyword

‘with’ 关键字用作引用对象属性或方法的一种速记。

作为 with 的参数指定的对象成为随后块的默认对象。可以在没有使用对象名称的情况下使用对象的属性和方法。

Syntax

with object 的语法如下 -

with (object) {
   properties used without the object name and dot
}

Example

尝试以下示例。

<html>
   <head>
   <title>User-defined objects</title>
      <script type = "text/javascript">
         // Define a function which will work as a method
         function addPrice(amount) {
            with(this) {
               price = amount;
            }
         }
         function book(title, author) {
            this.title = title;
            this.author = author;
            this.price = 0;
            this.addPrice = addPrice;  // Assign that method as property.
         }
      </script>
   </head>

   <body>
      <script type = "text/javascript">
         var myBook = new book("Perl", "Mohtashim");
         myBook.addPrice(100);

         document.write("Book title is : " + myBook.title + "<br>");
         document.write("Book author is : " + myBook.author + "<br>");
         document.write("Book price is : " + myBook.price + "<br>");
      </script>
   </body>
</html>

Output

Book title is : Perl
Book author is : Mohtashim
Book price is : 100

JavaScript Native Objects

JavaScript 有几个内置的或本地的对象。这些对象可以访问程序的任何地方,并且在运行于任何操作系统中的任何浏览器中都将以相同的方式工作。

以下是所有重要的 JavaScript 本地对象列表 -

JavaScript - The Number Object

Number 对象表示数值日期,无论是整数还是浮点数。通常,你不必担心 Number 对象,因为浏览器会自动将数字常量转换为数字类的实例。

Syntax

创建 number 对象的语法如下 -

var val = new Number(number);

在 number 的位置,如果你提供任何非数字参数,则参数不能转换为数字,则它返回 NaN (不是数字)。

Number Properties

以下列出每个属性和它们的说明。

Sr.No.

Property & Description

1

MAX_VALUE 一个数字在 JavaScript 中可以拥有的最大可能值 1.7976931348623157E+308

2

MIN_VALUE 一个数字在 JavaScript 中可以拥有的最小可能值 5E-324

3

NaN 等于非数字值。

4

NEGATIVE_INFINITY 小于 MIN_VALUE 的值。

5

POSITIVE_INFINITY 大于 MAX_VALUE 的值

6

prototype Number 对象的一个静态属性。使用原型属性向当前文档中的 Number 对象分配新属性和方法

7

constructor 返回创建此对象实例的函数。默认情况下,是 Number 对象。

在以下各节中,我们将举几个示例来说明 Number 的属性。

Number Methods

Number 对象仅包含作为每个对象定义的一部分的默认方法。

Sr.No.

Method & Description

1

toExponential() 强制一个数字以指数表示法显示,即使该数字处于 JavaScript 通常使用标准表示法的范围内。

2

toFixed() 以小数点右侧指定位数来格式化一个数字。

3

toLocaleString() 以字符串值形式返回当前数字,该格式可能根据浏览器的本地设置而有所不同。

4

toPrecision() 定义要显示数字的总位数(包括小数点左右的位数)。

5

toString() 返回数字值的字符串表示形式。

6

valueOf()Returns the number’s value.

在以下各节中,我们将举几个示例来说明 Number 的方法。

JavaScript - The Boolean Object

Boolean 对象表示两个值,“true”或“false”。如果省略了 value 参数或该参数为 0、-0、null、false、 NaN, undefined 或空字符串 (""),则对象初始值将为 false。

Syntax

使用以下语法创建 boolean 对象。

var val = new Boolean(value);

Boolean Properties

以下列出 Boolean 对象的属性:

Sr.No.

Property & Description

1

constructor 返回创建该对象的布尔函数的引用。

2

prototype prototype 属性允许您将属性和方法添加到对象。

在以下部分,我们将通过几个示例来说明布尔对象的属性。

Boolean Methods

以下是布尔对象的方法及其说明的列表。

Sr.No.

Method & Description

1

toSource() 返回包含布尔对象源的字符串;您可以使用此字符串创建等效的对象。

2

toString() 根据对象的值返回 “true” 或 “false” 字符串。

3

valueOf() 返回布尔对象的原始值。

在以下部分,我们将通过几个示例演示布尔方法的使用。

JavaScript - The Strings Object

String 对象允许您使用一系列字符;它用多个辅助方法包装 Javascript 字符串基元数据类型。

由于 JavaScript 会在字符串基元和 String 对象之间自动转换,因此您可以在字符串基元上调用 String 对象的任何辅助方法。

Syntax

使用以下语法创建 String 对象 −

var val = new String(string);

String 参数是已正确编码的一系列字符。

String Properties

以下是 String 对象的属性及其说明的列表。

Sr.No.

Property & Description

1

constructor 返回创建该对象的 String 函数的引用。

2

length 返回字符串的长度。

3

prototype prototype 属性允许您将属性和方法添加到对象。

在以下部分,我们将通过几个示例演示 String 属性的使用。

String Methods

以下是 String 对象中可用的方法及其说明的列表。

Sr.No.

Method & Description

1

charAt() 返回指定索引处的字符。

2

charCodeAt() 返回一个数字,表示给定索引处字符的 Unicode 值。

3

concat() 将两个字符串的文本组合并返回一个新字符串。

4

indexOf() 返回指定值在调用 String 对象中首次出现的索引,如果未找到,则返回 -1。

5

lastIndexOf() 返回指定值在调用 String 对象中最后出现的索引,如果未找到,则返回 -1。

6

localeCompare() 返回一个数字,指示参考字符串在排序顺序中在给定字符串之前、之后还是相同。

7

match() 用于将正则表达式与字符串进行匹配。

8

replace() 用于在正则表达式和字符串之间查找匹配并用新的子字符串替换匹配的子字符串。

9

search() 执行正则表达式和指定字符串之间的匹配搜索。

10

slice() 提取字符串的一部分并返回一个新字符串。

11

split() 通过将字符串分割成子字符串,将 String 对象分割成一个字符串数组。

12

substr() 返回从指定位置开始到指定字符数的字符串中的字符。

13

substring() 返回字符串中两个索引之间的字符。

14

toLocaleLowerCase() 字符串中的字符转换为小写,同时遵守当前区域设置。

15

toLocaleUpperCase() 字符串中的字符转换为大写,同时遵守当前区域设置。

16

toLowerCase() 返回转换为小写的调用字符串值。

17

toString() 返回表示指定对象的字符串。

18

toUpperCase() 返回转换为大写的调用字符串值。

19

valueOf() 返回指定对象的原始值。

String HTML Wrappers

以下是返回用适当的 HTML 标签包装的字符串副本的方法列表。

Sr.No.

Method & Description

1

anchor() 创建一个用作超文本目标的 HTML 锚点。

2

big() 创建一个大字体文本,就好像它在一个 <big> 标签内一样。

3

blink() 创建一个闪烁文本,就好像它在一个 <blink> 标签内一样。

4

bold() 创建一个粗体文本,就好像它在一个 <b> 标签内一样。

5

fixed() 导致一个文本以固定间距字体显示,就好像它在一个 <tt> 标签内一样。

6

fontcolor() 导致一个文本以指定颜色显示,就好像它在一个 <font color="color"> 标签内一样。

7

fontsize() 导致一个文本以指定字体大小显示,就好像它在一个 <font size="size"> 标签内一样。

8

italics() 导致一个文本变成斜体,就好像它在一个 <i> 标签内一样。

9

link() 创建一个请求另一个 URL 的 HTML 超文本链接。

10

small() 导致一个文本以小字体显示,就好像它在一个 <small> 标签内一样。

11

strike() 导致一个文本以删除线文本显示,就好像它在一个 <strike> 标签内一样。

12

sub() 导致一个文本以下标显示,就好像它在一个 <sub> 标签内一样。

13

sup() 导致一个文本以上标显示,就好像它在一个 <sup> 标签内一样。

在以下部分中,我们将演示几个示例来展示 String 方法的用法。

JavaScript - The Arrays Object

Array 对象允许您在单个变量中存储多个值。它存储一个相同类型的元素组成的固定大小顺序集合。数组用于存储数据集合,但通常将其视为同一类型的变量集合更有用。

Syntax

使用以下语法创建 Array 对象 −

var fruits = new Array( "apple", "orange", "mango" );

Array 参数是字符串或整数的列表。当您使用 Array 构造函数指定单个数字参数时,将指定数组的初始长度。一个数组允许的最大长度为 4,294,967,295。

您可以通过简单地分配值来创建数组,如下所示 −

var fruits = [ "apple", "orange", "mango" ];

你将使用序数来访问并设置数组中的值,如下所示。

fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element

Array Properties

以下是 Array 对象的属性列表及其描述。

Sr.No.

Property & Description

1

constructor 返回对创建对象的数组函数的引用。

2

index 该属性表示字符串中匹配项的从零开始的索引

3

input 此属性仅出现在由正则表达式匹配创建的数组中。

4

length 反映数组中元素的数量。

5

prototype prototype 属性允许您将属性和方法添加到对象。

在以下部分中,我们将举几个示例来说明 Array 属性的用法。

Array Methods

下面列出了 Array 对象的方法及其描述。

Sr.No.

Method & Description

1

concat() 返回一个新数组,包括该数组与其他数组和/或值连接而成。

2

every() 如果该数组中的每个元素都满足所提供的测试函数,则返回 true。

3

filter() 使用所提供的筛选函数返回 true 的该数组的所有元素创建一个新数组。

4

forEach() 为数组中的每个元素调用一个函数。

5

indexOf() 返回数组中与指定值相等的元素的第一个(最小)索引,如果未找到,则返回 -1。

6

join() 把数组中的所有元素连接成一个字符串。

7

lastIndexOf() 返回数组中与指定值相等的元素的最后一个(最大的)索引,如果未找到,则返回 -1。

8

map() 创建一个新数组,其中包含对该数组中每个元素调用所提供函数的结果。

9

pop() 从数组中移除最后一个元素并返回该元素。

10

push() 向数组的末尾添加一个或多个元素,并返回数组的新长度。

11

reduce() 将一个函数同时应用于数组的两个值(从左到右)将其简化为一个值。

12

reduceRight() 将一个函数同时应用于数组的两个值(从右到左)将其简化为一个值。

13

reverse() 反转数组中元素的顺序——第一个变为最后一个,最后一个变为第一个。

14

shift() 从数组中移除第一个元素并返回该元素。

15

slice() 截取数组的一部分, 返回一个新数组。

16

some() 若至少一个元素通过测试函数, 则返回 true。

17

toSource() 表示对象的源代码。

18

sort() 对数组元素进行排序。

19

splice() 添加或删除数组中的元素。

20

toString() 返回表示数组及其元素的字符串。

21

unshift() 在数组开头添加一个或多个元素, 并返回数组的新长度。

在下几节中, 我们将通过示例说明数组方法的使用。

JavaScript - The Date Object

Date 对象是 JavaScript 语言中内置的数据类型。可使用 new Date( ) 创建 Date 对象, 如下所示。

创建 Date 对象后, 多个方法允许你对其进行操作。大部分方法仅允许你获取和设置对象的年、月、日、小时、分钟、秒和毫秒字段, 使用本地时间或 UTC (通用或 GMT) 时间。

ECMAScript 标准要求 Date 对象能表示任意日期和时间, 至毫秒精度, 于 1/1/1970 前后 1 亿天内。这是正负 273,785 年的范围, 因此 JavaScript 可以表示到 275755 年的日期和时间。

Syntax

你可以使用下列任意语法来使用 Date() 构造函数创建 Date 对象。

new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])

Note − 括号中的参数始终为可选。

以下是参数说明 −

  1. No Argument − 无参数时, Date() 构造函数创建了一个设定为当前日期和时间的 Date 对象。

  2. milliseconds − 传递一个数字参数时, 它将按 getTime() 方法返回的内容进行指定为该日期的内部数字表示形式 (以毫秒为单位)。例如, 传递的参数 5000 即表示 1/1/70 00:00:05。

  3. datestring − 传递一个字符串参数时, 它将按 Date.parse() 方法接受的格式指定一个日期的字符串表示形式。

  4. 7 agruments − 若要使用上面显示的构造函数的最后一种形式。以下是每个参数的说明 −

Date Properties

以下是 Date 对象的属性列表及其描述。

Sr.No.

Property & Description

1

constructor 指定创建对象原型的函数。

2

prototype prototype 属性使您可以向对象添加属性和方法。

在以下部分中,我们将提供一些示例以演示不同日期属性的用法。

Date Methods

下面列出了 Date 中使用的方法及其说明。

Sr.No.

Method & Description

1

Date() 返回今天的日期和时间。

2

getDate() 根据当地时间返回指定日期的月份中的天数。

3

getDay() 根据当地时间返回指定日期的星期几。

4

getFullYear() 根据当地时间返回指定日期的年份。

5

getHours() 根据当地时间返回指定日期的小时数。

6

getMilliseconds() 根据当地时间返回指定日期的毫秒数。

7

getMinutes() 根据当地时间返回指定日期的分钟数。

8

getMonth() 根据当地时间返回指定日期的月份。

9

getSeconds() 根据当地时间返回指定日期的秒数。

10

getTime() 将指定日期的数值(自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的毫秒数)作为数字值返回。

11

getTimezoneOffset() 返回当前区域设置的时间偏移(以分钟为单位)。

12

getUTCDate() 根据世界时返回指定日期中月份中的天数(日期)。

13

getUTCDay() 根据世界时返回指定日期的星期几。

14

getUTCFullYear() 根据世界时返回指定日期的年份。

15

getUTCHours() 根据世界时返回指定日期的小时数。

16

getUTCMilliseconds() 返回指定的日期中的毫秒,按世界时计算。

17

getUTCMinutes() 返回指定的日期中的分钟,按世界时计算。

18

getUTCMonth() 返回指定的日期中的月份,按世界时计算。

19

getUTCSeconds() 返回指定的日期中的秒,按世界时计算。

20

getYear() Deprecated - 返回指定的日期中的年份,按本地时间计算。请改用 getFullYear。

21

setDate() 设置指定的日期中月份中的某一天,按本地时间计算。

22

setFullYear() 设置指定的日期的完整年份,按本地时间计算。

23

setHours() 设置指定的日期中的小时,按本地时间计算。

24

setMilliseconds() 设置指定的日期中的毫秒,按本地时间计算。

25

setMinutes() 设置指定的日期中的分钟,按本地时间计算。

26

setMonth() 设置指定的日期的月份,按本地时间计算。

27

setSeconds() 设置指定的日期中的秒,按本地时间计算。

28

setTime() 设置 Date 对象为以自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的毫秒数表示的时间。

29

setUTCDate() 设置指定的日期中月份中的某一天,按世界时计算。

30

setUTCFullYear() 设置指定的日期的完整年份,按世界时计算。

31

setUTCHours() 设置指定的日期中的小时,按世界时计算。

32

setUTCMilliseconds() 设置指定的日期中的毫秒,按世界时计算。

33

setUTCMinutes() 设置指定的日期中的分钟,按世界时计算。

34

setUTCMonth() 设置指定的日期中的月份,按世界时计算。

35

setUTCSeconds() 根据世界时设置指定日期的秒。

36

setYear() *已弃用 - * 根据当前时间设置指定日期的年。改为使用 setFullYear。

37

toDateString() 将 Date 的“日期”部分返回为人类可读的字符串。

38

toGMTString() *已弃用 - * 使用 Internet GMT 约定将日期转换为字符串。改为使用 toUTCString。

39

toLocaleDateString() 根据当前区域设置的约定将 Date 的“日期”部分返回为字符串。

40

toLocaleFormat() 使用格式字符串将日期转换为字符串。

41

toLocaleString() 根据当前区域设置的约定将日期转换为字符串。

42

toLocaleTimeString() 根据当前区域设置的约定将 Date 的“时间”部分返回为字符串。

43

toSource() 返回一个字符串,表示等效 Date 对象的源;可以使用此值来创建一个新对象。

44

toString() 返回一个字符串,表示指定的 Date 对象。

45

toTimeString() 将 Date 的“时间”部分返回为人类可读的字符串。

46

toUTCString() 使用世界时约定将日期转换为字符串。

47

valueOf() 返回 Date 对象的原始值。

使用世界时约定将日期转换为字符串。

Date Static Methods

除了先前列出的许多实例方法外,Date 对象还定义了两个静态方法。这些方法通过 Date() 构造函数本身调用。

Sr.No.

Method & Description

1

Date.parse( ) 解析日期和时间的字符串表示形式并返回该日期的内部毫秒表示形式。

2

Date.UTC( ) 返回指定的 UTC 日期和时间的毫秒表示形式。

在以下部分中,我们将通过一些示例来演示 Date 静态方法的使用。

JavaScript - The Math Object

math 对象提供数学常数和函数的属性和方法。与其他全局对象不同, Math 不是构造函数。 Math 的所有属性和方法都是静态的,可以通过将 Math 用作对象而不创建它来调用。

因此,你可以引用 Math.PI 中的 pi 常量,并且你可以将 Math.sin(x) 调用为正弦函数,其中 x 是该方法的参数。

Syntax

调用 Math 的属性和方法的语法如下所述:

var pi_val = Math.PI;
var sine_val = Math.sin(30);

Math Properties

以下是 Math 的所有属性及其描述的列表。

Sr.No.

Property & Description

1

href:../javascript/math_e.html[E\]欧拉常数和自然对数的底,约为 2.718。

2

LN2 2 的自然对数,约为 0.693。

3

LN10 10 的自然对数,约为 2.302。

4

LOG2E E 的以 2 为底的对数,约为 1.442。

5

LOG10E E 的以 10 为底的对数,约为 0.434。

6

PI 圆的周长与其直径的比率,约为 3.14159。

7

SQRT1_2 1/2 的平方根;等价于 1 除以 2 的平方根,约为 0.707。

8

SQRT2 2 的平方根,约为 1.414。

在以下部分中,我们将提供一些示例来说明如何使用 Math 属性。

Math Methods

以下是与 Math 对象关联的方法及其描述的列表:

Sr.No.

Method & Description

1

abs() 返回一个数字的绝对值。

2

acos() 以弧度为单位返回一个数字的反余弦值。

3

asin() 以弧度为单位返回一个数字的反正弦值。

4

atan() 返回一个数字的反正切值(以弧度为单位)。

5

atan2() 返回其参数商的反正切值。

6

ceil() 返回大于或等于一个数的最小整数。

7

cos() 返回一个数的余弦。

8

exp() 返回 EN,其中 N 为参数,E 是欧拉常数,自然对数的底数。

9

floor() 返回小于或等于一个数的最大整数。

10

log() 返回一个数的自然对数(以 E 为底)。

11

max() 返回零或多个数字中最大的数字。

12

min() 返回零或多个数字中最小的数字。

13

pow() 以底数的指数形式返回底数,即底数指数。

14

random() 返回 0 到 1 之间的伪随机数。

15

round() 返回舍入到最接近整数的值。

16

sin() 返回数字的正弦。

17

sqrt() 返回数字的平方根。

18

tan() 返回数字的正切。

19

toSource()Returns the string "Math".

在以下部分中,我们将通过一些示例来说明与 Math 关联的方法的用法。

Regular Expressions and RegExp Object

正则表达式是一个对象,描述一个字符模式。

JavaScript RegExp 类表示正则表达式,并且 String 和 RegExp 都定义了使用正则表达式来对文本执行强大的模式匹配和搜索替换功能的方法。

Syntax

正则表达式可以用 RegExp () 构造函数定义,如下所示:

var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;

以下是参数说明 −

  1. pattern − 一个字符串,指定正则表达式的模式或另一个正则表达式。

  2. attributes − 一个可选字符串,包含任何表示全局、不区分大小写和多行匹配的“g”、“i”和“m”属性。

Brackets

括号 ([]) 在正则表达式中使用时具有特殊的含义。它们用于查找字符范围。

Sr.No.

Expression & Description

1

[&#8230;&#8203;] 括号内的任何一个字符。

2

[^&#8230;&#8203;] 括号外的任何一个字符。

3

[0-9] 它匹配 0 到 9 之间的任何十进制数字。

4

[a-z] 它匹配小写 a *through lowercase *z 中的任何字符。

5

[A-Z] 它匹配大写 A 到大写 Z 中的任何字符。

6

[a-Z] 它匹配小写 a 到大写 Z 中的任何字符。

上面显示的范围是通用的;你还可以使用范围 [0-3] 匹配 0 到 3 之间的任何十进制数字,或者使用范围 [b-v] 匹配小写 bv 之间的任何小写字符。

Quantifiers

括号字符序列和单个字符的频率或位置可以通过特殊字符表示。每个特殊字符都有特定的含义。+, *, ?, 和 $ 标志都跟随一个字符序列。

Sr.No.

Expression & Description

1

p+ 它匹配包含一个或多个 p 的任何字符串。

2

p *匹配包含零个或更多个 p 的任何字符串。

3

p? 匹配包含不超过一个 p 的任何字符串。

4

p{N} 匹配包含 N p 序列的任何字符串

5

p{2,3} 匹配包含两个或三个 p 序列的任何字符串。

6

p{2, } 匹配包含至少两个 p 序列的任何字符串。

7

p$ 匹配末尾有 p 的任何字符串。

8

^p 匹配开头有 p 的任何字符串。

Examples

以下示例详细解释了如何匹配字符。

Sr.No.

Expression & Description

1

[^a-zA-Z] 匹配不包含 azA 及其之后的 Z 范围内任何字符的任何字符串。

2

p.p 匹配包含 p, ,随后是任意字符,而后依次是另一个 p 的任何字符串。

3

^.{2}$ 匹配包含正好两个字符的任何字符串。

4

&lt;b&gt;(. )</b>*匹配以 <b> 和 </b> 括起的任何字符串。

5

p(hp) 匹配包含 *p 然后是零个或多个 hp 序列实例的任何字符串。

Literal characters

Sr.No.

Character & Description

1

Alphanumeric Itself

2

\0 The NUL character (\u0000)

3

\t Tab (\u0009

4

\n Newline (\u000A)

5

\v Vertical tab (\u000B)

6

\f Form feed (\u000C)

7

\r Carriage return (\u000D)

8

\xnn 十六进制数字 nn 指定的拉丁字符;例如,\x0A 等同于 \n

9

\uxxxx 十六进制数字 xxxx 指定的 Unicode 字符;例如,\u0009 等同于 \t

10

\cX 控制字符 ^X;例如,\cJ 等于换行符 \n

Metacharacters

元字符只是一个字母字符,后面跟着一个反斜杠,用于赋予该组合特殊含义。

例如,可以使用“\d”元字符搜索一大笔钱: /([\d]+)000/ ,此处 \d 将搜索包含所有数字字符的字符串。

下表列出了可在 PERL 样式正则表达式中使用的元字符。

Sr.No.

Character & Description

1

. a single character

2

\s 一个空白字符(空格、制表符、换行符)

3

\S non-whitespace character

4

\d a digit (0-9)

5

\D a non-digit

6

\w 一个单词字符(a-z、A-Z、0-9、_)

7

\W a non-word character

8

[\b] 一个反斜杠文字(特殊情况)。

9

[aeiou] 匹配给定集合中的单个字符。

10

[^aeiou] 匹配给定集合之外的单个字符。

11

*(foo

bar

baz)* 匹配指定的所有选项。

Modifiers

几种修饰符可以简化使用 regexps, 的方式,例如大小写敏感、多行搜索等。

Sr.No.

Modifier & Description

1

i Perform case-insensitive matching.

2

m 指明如果字符串有换行符或回车字符,^ 和 $ 运算符现在会匹配换行边界,而不是字符串边界。

3

g 执行全局匹配,即查找所有匹配,而不是在找到第一个匹配后停止。

RegExp Properties

以下是与 RegExp 相关的属性及其描述的列表。

Sr.No.

Property & Description

1

constructor 指定创建一个对象的原型的函数。

2

global 指定是否设置了“g”修饰符。

3

ignoreCase 指定是否设置了“i”修饰符。

4

lastIndex 开始下一次匹配的索引。

5

multiline 指定是否设置了“m”修饰符。

6

source 模式的文本。

在以下部分中,我们将提供一些示例来说明 RegExp 属性的用法。

RegExp Methods

以下是与 RegExp 相关的函数及其描述的列表。

Sr.No.

Method & Description

1

exec() 在字符串参数中执行搜索以查找匹配。

2

test() 在其字符串参数中测试匹配项。

3

toSource() 返回一个表示指定对象的字面量对象;可使用此值创建新对象。

4

toString() 返回一个表示指定对象的字符串。

在以下几个部分中,我们将列出一些示例来说明正则表达式方法的使用。

JavaScript - Document Object Model or DOM

每个网页都驻留在浏览器窗口内,该浏览器窗口可视为一个对象。

Document 对象表示显示在该窗口中的 HTML 文档。Document 对象具有各种属性,这些属性引用其他对象,用于允许访问和修改文档内容。

访问和修改文档内容的方式称为 Document Object ModelDOM 。对象按层次结构组织。此层次结构适用于 Web 文档中对象的组织。

  1. Window object − 层次结构的顶部。它是对象层次结构中最外层的元素。

  2. Document object − 加载到窗口中的每个 HTML 文档都会成为文档对象。文档包含页面内容。

  3. Form object − <form>…​</form> 标记中包含的所有内容都会设置 form 对象。

  4. Form control elements − form 对象包含为该对象定义的所有元素,如文本字段、按钮、单选按钮和复选框。

以下是几个重要对象的简单层次结构−

html dom

存在多个 DOM。以下几个部分详细说明了每个 DOM,并描述了如何使用这些 DOM 来访问和修改文档内容。

  1. The Legacy DOM − 这是在早期版本的 JavaScript 语言中引入的模型。它得到了所有浏览器的良好支持,但只允许访问文档的某些关键部分,例如表单、表单元素和图像。

  2. The W3C DOM − 这种文档对象模型允许访问和修改所有文档内容,并由万维网联盟 (W3C) 标准化。此模型得到几乎所有现代浏览器的支持。

  3. The IE4 DOM − 这种文档对象模型是在 Microsoft 的 Internet Explorer 浏览器版本 4 中引入的。IE 5 及更高版本支持大多数基本的 W3C DOM 功能。

DOM compatibility

如果要编写一个脚本来灵活地根据其可用性使用 W3C DOM 或 IE 4 DOM,那么可以使用功能测试方法,该方法首先检查某个方法或属性是否存在,以确定浏览器是否具有你所希望的功能。例如:

if (document.getElementById) {
   // If the W3C method exists, use it
} else if (document.all) {
   // If the all[] array exists, use it
} else {
   // Otherwise use the legacy DOM
}

JavaScript - Errors & Exceptions Handling

编程中有三类错误:(a) 语法错误、(b) 运行时错误和 (c) 逻辑错误。

Syntax Errors

语法错误,也称为 parsing errors, 发生在传统编程语言的编译时和 JavaScript 的解释时。

例如,以下行会引发语法错误,因为它缺少一个结束括号。

<script type = "text/javascript">
   <!--
      window.print(;
   //-->
</script>

当 JavaScript 中发生一个语法错误时,仅包含与该语法错误位于同一线程中的代码会受到影响,而其他线程中的其余代码会按假设它们不依赖于包含该错误的代码的方式执行。

Runtime Errors

运行时错误,也称作 exceptions, 发生在执行期间(在编译/解释之后)。

例如,以下行会引发运行时错误,这是因为此处的语法正确,但在运行时它试图调用一个不存在的方法。

<script type = "text/javascript">
   <!--
      window.printme();
   //-->
</script>

异常也会影响它们发生的线程,允许其他 JavaScript 线程继续正常执行。

Logical Errors

逻辑错误可能是最难追踪的错误类型。这些错误并非由语法或运行时错误导致的。它们发生在你的脚本的驱动逻辑中出现错误时,且你未得到预期的结果。

你无法捕获这些错误,因为你想要在你的程序中置入哪种类型的逻辑取决于你的业务需求。

The try…​catch…​finally Statement

最新版本的 JavaScript 添加了异常处理能力。JavaScript 实现 try…​catch…​finally 结构和 throw 运算符来处理异常。

你可以 catch 由程序员产生的和 runtime 异常,但你不能 catch JavaScript 语法错误。

以下为 try…​catch…​finally 块语法 −

<script type = "text/javascript">
   <!--
      try {
         // Code to run
         [break;]
      }

      catch ( e ) {
         // Code to run if an exception occurs
         [break;]
      }

      [ finally {
         // Code that is always executed regardless of
         // an exception occurring
      }]
   //-->
</script>

try 块必须紧跟一个 catch 块或一个 finally 块(或者两者)。当在 try 块中发生异常时,该异常被置入 e 中,且 catch 块被执行。可选的 finally 块会在 try/catch 之后无条件执行。

Examples

以下是一个我们试图调用一个不存在的函数的示例,该函数会引发异常。让我们看看在没有 try…​catch 的情况下它的表现 −

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function myFunc() {
               var a = 100;
               alert("Value of variable a is : " + a );
            }
         //-->
      </script>
   </head>

   <body>
      <p>Click the following to see the result:</p>

      <form>
         <input type = "button" value = "Click Me" onclick = "myFunc();" />
      </form>
   </body>
</html>

Output

现在让我们尝试使用 try…​catch 捕获此异常并显示一条用户友好的消息。如果想对用户隐藏此错误,你也可以禁止显示此消息。

<html>
   <head>

      <script type = "text/javascript">
         <!--
            function myFunc() {
               var a = 100;
               try {
                  alert("Value of variable a is : " + a );
               }
               catch ( e ) {
                  alert("Error: " + e.description );
               }
            }
         //-->
      </script>

   </head>
   <body>
      <p>Click the following to see the result:</p>

      <form>
         <input type = "button" value = "Click Me" onclick = "myFunc();" />
      </form>

   </body>
</html>

Output

你可以使用 finally 块,它会一直无条件地执行,在 try/catch 之后。以下是一个示例。

<html>
   <head>

      <script type = "text/javascript">
         <!--
            function myFunc() {
               var a = 100;

               try {
                  alert("Value of variable a is : " + a );
               }
               catch ( e ) {
                  alert("Error: " + e.description );
               }
               finally {
                  alert("Finally block will always execute!" );
               }
            }
         //-->
      </script>

   </head>
   <body>
      <p>Click the following to see the result:</p>

      <form>
         <input type = "button" value = "Click Me" onclick = "myFunc();" />
      </form>

   </body>
</html>

Output

The throw Statement

你可以使用 throw 语句引发你内置的异常或自定义的异常。之后可以捕获这些异常,你可以采取适当的行动。

Example

以下示例演示了如何使用 throw 语句。

<html>
   <head>

      <script type = "text/javascript">
         <!--
            function myFunc() {
               var a = 100;
               var b = 0;

               try {
                  if ( b == 0 ) {
                     throw( "Divide by zero error." );
                  } else {
                     var c = a / b;
                  }
               }
               catch ( e ) {
                  alert("Error: " + e );
               }
            }
         //-->
      </script>

   </head>
   <body>
      <p>Click the following to see the result:</p>

      <form>
         <input type = "button" value = "Click Me" onclick = "myFunc();" />
      </form>

   </body>
</html>

Output

你可以在一个函数中使用字符串、整数、布尔值或对象引发异常,然后你可以在同函数(如上所述)或使用 try…​catch 块在另一个函数中捕获该异常。

The onerror() Method

onerror 事件处理程序是第一项允许在 JavaScript 中进行错误处理的功能。无论在页面上发生什么异常, error 事件都会在 window 对象上触发。

<html>
   <head>

      <script type = "text/javascript">
         <!--
            window.onerror = function () {
               alert("An error occurred.");
            }
         //-->
      </script>

   </head>
   <body>
      <p>Click the following to see the result:</p>

      <form>
         <input type = "button" value = "Click Me" onclick = "myFunc();" />
      </form>

   </body>
</html>

Output

onerror 事件处理程序提供三项信息来识别错误的确切性质 −

  1. Error message − 浏览器将针对给定错误显示的相同消息

  2. URL − 发生错误的文件

  3. Line number - 给定 URL 中导致该错误的行号

以下示例展示了如何提取此信息。

Example

<html>
   <head>

      <script type = "text/javascript">
         <!--
            window.onerror = function (msg, url, line) {
               alert("Message : " + msg );
               alert("url : " + url );
               alert("Line number : " + line );
            }
         //-->
      </script>

   </head>
   <body>
      <p>Click the following to see the result:</p>

      <form>
         <input type = "button" value = "Click Me" onclick = "myFunc();" />
      </form>

   </body>
</html>

Output

你可以以你认为更合适的方式显示提取出的信息。

你可以使用以下所示的` onerror `方法,在加载图片时出现任何问题的时候,显示错误信息。

<img src="myimage.gif" onerror="alert('An error occurred loading the image.')" />

你可以使用` onerror `结合许多HTML标签,在出现错误的时候显示适当的消息。

JavaScript - Form Validation

表单验证通常在客户端输入所有必要数据并按下了提交按钮后在服务器上发生。如果客户端输入的数据不正确或丢失,服务器将不得不将所有数据发送回客户端,并要求使用正确的信息重新提交该表单。这确实是一个冗长的过程,过去给服务器带来了很大的负担。

Javascript 提供了一种方法,可以在将表单数据发送到 Web 服务器之前在客户端计算机上验证其数据。表单验证通常执行两个功能。

  1. Basic Validation - 首先,必须检查表单以确保所有必填字段已填入。这只需要循环遍历表单中的每个字段并检查数据。

  2. Data Format Validation - 其次,必须检查输入的数据是否具有正确的形式和 value。你的代码必须包含适当的逻辑来测试数据的正确性。

Example

我们将通过一个例子来了解验证的过程。以下是一个 html 格式的简单表单。

<html>
   <head>
      <title>Form Validation</title>
      <script type = "text/javascript">
         <!--
            // Form validation code will come here.
         //-->
      </script>
   </head>

   <body>
      <form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit = "return(validate());">
         <table cellspacing = "2" cellpadding = "2" border = "1">

            <tr>
               <td align = "right">Name</td>
               <td><input type = "text" name = "Name" /></td>
            </tr>

            <tr>
               <td align = "right">EMail</td>
               <td><input type = "text" name = "EMail" /></td>
            </tr>

            <tr>
               <td align = "right">Zip Code</td>
               <td><input type = "text" name = "Zip" /></td>
            </tr>

            <tr>
               <td align = "right">Country</td>
               <td>
                  <select name = "Country">
                     <option value = "-1" selected>[choose yours]</option>
                     <option value = "1">USA</option>
                     <option value = "2">UK</option>
                     <option value = "3">INDIA</option>
                  </select>
               </td>
            </tr>

            <tr>
               <td align = "right"></td>
               <td><input type = "submit" value = "Submit" /></td>
            </tr>

         </table>
      </form>
   </body>
</html>

Output

Basic Form Validation

首先让我们看看如何执行基本表单验证。在上述表单中,我们调用 validate() 以在 onsubmit 事件发生时验证数据。以下代码显示了该 validate() 函数的实现。

<script type = "text/javascript">
   <!--
      // Form validation code will come here.
      function validate() {

         if( document.myForm.Name.value == "" ) {
            alert( "Please provide your name!" );
            document.myForm.Name.focus() ;
            return false;
         }
         if( document.myForm.EMail.value == "" ) {
            alert( "Please provide your Email!" );
            document.myForm.EMail.focus() ;
            return false;
         }
         if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) ||
            document.myForm.Zip.value.length != 5 ) {

            alert( "Please provide a zip in the format #####." );
            document.myForm.Zip.focus() ;
            return false;
         }
         if( document.myForm.Country.value == "-1" ) {
            alert( "Please provide your country!" );
            return false;
         }
         return( true );
      }
   //-->
</script>

Data Format Validation

现在,我们将看到如何在提交到 Web 服务器之前验证我们的已输入表单数据。

以下示例显示了如何验证输入的电子邮件地址。电子邮件地址必须至少包含一个“@”符号和一个点(.)。此外,“@”不能是电子邮件地址的第一个字符,而最后一个点必须至少是“@”符号之后的一个字符。

Example

尝试以下代码进行电子邮件验证。

<script type = "text/javascript">
   <!--
      function validateEmail() {
         var emailID = document.myForm.EMail.value;
         atpos = emailID.indexOf("@");
         dotpos = emailID.lastIndexOf(".");

         if (atpos < 1 || ( dotpos - atpos < 2 )) {
            alert("Please enter correct email ID")
            document.myForm.EMail.focus() ;
            return false;
         }
         return( true );
      }
   //-->
</script>

JavaScript - Animation

你可以使用 JavaScript 创建一个复杂的动画,包括但不限于以下元素:

  1. Fireworks

  2. Fade Effect

  3. Roll-in or Roll-out

  4. Page-in or Page-out

  5. Object movements

你可能对现有的基于 JavaScript 的动画库感兴趣: Script.Aculo.us

本教程提供了如何使用 JavaScript 来创建动画的基本理解。

JavaScript 可用于移动一些 DOM 元素(<img/>、<div> 或任何其他 HTML 元素)在页面上依据由逻辑方程式或函数确定的某种样式进行移动。

JavaScript 提供了以下两个函数,在动画程序中经常使用。

  1. setTimeout( function, duration) − 此函数在从现在起 duration 毫秒后调用 function

  2. setInterval(function, duration) − 此函数每隔 duration 毫秒调用一次 function

  3. clearTimeout(setTimeout_variable) − 此函数调用清除 setTimeout() 函数设置的任何计时器。

JavaScript 还可以设置 DOM 对象的多个属性,包括它在屏幕上的位置。你可以设置对象的上和左属性,以将其定位在屏幕上的任何位置。下面是它的语法。

// Set distance from left edge of the screen.
object.style.left = distance in pixels or points;

or

// Set distance from top edge of the screen.
object.style.top = distance in pixels or points;

Manual Animation

因此,让我们实现一个使用 DOM 对象属性和 JavaScript 函数的简单动画,如下所示。以下列表包含不同的 DOM 方法。

  1. 我们正在使用 getElementById() JavaScript 函数获取 DOM 对象,然后将其分配给全局变量 imgObj

  2. 我们定义了一个初始化函数 init() 来初始化 imgObj ,我们在此设置了它的 positionleft 属性。

  3. 我们正在窗口加载时调用初始化函数。

  4. 最后,我们正在调用 moveRight() 函数以将左距离增加 10 个像素。你还可以将其设置为负值以将其移动到左侧。

Example

尝试以下示例。

<html>
   <head>
      <title>JavaScript Animation</title>
      <script type = "text/javascript">
         <!--
            var imgObj = null;

            function init() {
               imgObj = document.getElementById('myImage');
               imgObj.style.position= 'relative';
               imgObj.style.left = '0px';
            }
            function moveRight() {
               imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
            }

            window.onload = init;
         //-->
      </script>
   </head>

   <body>
      <form>
         <img id = "myImage" src = "/images/html.gif" />
         <p>Click button below to move the image to right</p>
         <input type = "button" value = "Click Me" onclick = "moveRight();" />
      </form>
   </body>
</html>

Output

Automated Animation

在以上示例中,我们看到了图像如何随着每次点击向右移动。我们可以通过使用 JavaScript 函数 setTimeout() 自动化此过程,如下所示 −

这里我们添加了更多方法。所以,让我们看看这里有哪些新增内容 −

  1. moveRight() 函数正在调用 setTimeout() 函数来设置 imgObj 的位置。

  2. 我们添加了一个新函数 stop() 来清除 setTimeout() 函数设置的计时器,并将其对象设置在其初始位置。

Example

尝试以下示例代码。

<html>
   <head>
      <title>JavaScript Animation</title>
      <script type = "text/javascript">
         <!--
            var imgObj = null;
            var animate ;

            function init() {
               imgObj = document.getElementById('myImage');
               imgObj.style.position= 'relative';
               imgObj.style.left = '0px';
            }
            function moveRight() {
               imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
               animate = setTimeout(moveRight,20);    // call moveRight in 20msec
            }
            function stop() {
               clearTimeout(animate);
               imgObj.style.left = '0px';
            }

            window.onload = init;
         //-->
      </script>
   </head>

   <body>
      <form>
         <img id = "myImage" src = "/images/html.gif" />
         <p>Click the buttons below to handle animation</p>
         <input type = "button" value = "Start" onclick = "moveRight();" />
         <input type = "button" value = "Stop" onclick = "stop();" />
      </form>
   </body>
</html>

Rollover with a Mouse Event

这是一个显示鼠标事件图像翻转效果的简单示例。

让我们看看我们在以下示例中使用了什么 −

  1. 在加载此页面时,“if” 语句将检查图像对象是否存在。如果图像对象不可用,则此块将不会被执行。

  2. Image() 构造函数创建一个并预加载名为 image1 的新图像对象。

  3. 为 src 属性指定名为 /images/html.gif 的外部图像文件的名字。

  4. 同样,我们创建了 image2 对象并在该对象中指定了 /images/http.gif。

  5. #(数字符号)禁用链接,以便浏览器在单击时不会尝试转到 URL。此链接是一个图像。

  6. 当用户鼠标移到链接上时,触发 onMouseOver 事件处理程序;当用户鼠标移开链接(图像)时,触发 onMouseOut 事件处理程序。

  7. 当鼠标移到图像上时,HTTP 图像将从第一张图像更改为第二张图像。当鼠标移开图像时,将显示原始图像。

  8. 鼠标移开链接后,起始图像 html.gif 将会重新显示在界面上。

<html>

   <head>
      <title>Rollover with a Mouse Events</title>

      <script type = "text/javascript">
         <!--
            if(document.images) {
               var image1 = new Image();     // Preload an image
               image1.src = "/images/html.gif";
               var image2 = new Image();     // Preload second image
               image2.src = "/images/http.gif";
            }
         //-->
      </script>
   </head>

   <body>
      <p>Move your mouse over the image to see the result</p>

      <a href = "#" onMouseOver = "document.myImage.src = image2.src;"
         onMouseOut = "document.myImage.src = image1.src;">
         <img name = "myImage" src = "/images/html.gif" />
      </a>
   </body>
</html>

JavaScript - Multimedia

JavaScript` navigator 对象包括一个名为 plugins `的子对象。这个对象是一个数组,其中有一个浏览器上已安装的每个插件的条目。`navigator.plugins`对象仅受Netscape、Firefox和Mozilla支持。

Example

下面是一个示例,它展示了如何列出你的浏览器中安装的所有插件:

<html>
   <head>
      <title>List of Plug-Ins</title>
   </head>

   <body>
      <table border = "1">
         <tr>
            <th>Plug-in Name</th>
            <th>Filename</th>
            <th>Description</th>
         </tr>

         <script language = "JavaScript" type = "text/javascript">
            for (i = 0; i<navigator.plugins.length; i++) {
               document.write("<tr><td>");
               document.write(navigator.plugins[i].name);
               document.write("</td><td>");
               document.write(navigator.plugins[i].filename);
               document.write("</td><td>");
               document.write(navigator.plugins[i].description);
               document.write("</td></tr>");
            }
         </script>
      </table>
   </body>
</html>

Output

Checking for Plug-Ins

每个插件在数组中都有一个条目。每个条目有以下的属性:

  1. ` name ` - 插件的名称。

  2. ` filename ` - 加载插件时执行的文件。

  3. ` description ` - 插件的描述(由开发者提供)。

  4. ` mimeTypes ` - 一个数组,其中有一个插件支持的每一MIME类型的条目。

你可以在脚本中使用这些属性来找出已安装的插件,然后使用JavaScript播放适当的多媒体文件。看看下面的示例。

<html>
   <head>
      <title>Using Plug-Ins</title>
   </head>

   <body>
      <script language = "JavaScript" type = "text/javascript">
         media = navigator.mimeTypes["video/quicktime"];

         if (media) {
            document.write("<embed src = 'quick.mov' height = 100 width = 100>");
         } else {
            document.write("<img src = 'quick.gif' height = 100 width = 100>");
         }
      </script>
   </body>
</html>

Output

` NOTE ` - 我们在这里使用HTML`<embed>`标签嵌入多媒体文件。

Controlling Multimedia

让我们举一个在几乎所有浏览器中都适用的真实示例:

<html>
   <head>
      <title>Using Embeded Object</title>

      <script type = "text/javascript">
         <!--
            function play() {
               if (!document.demo.IsPlaying()) {
                  document.demo.Play();
               }
            }
            function stop() {
               if (document.demo.IsPlaying()) {
                  document.demo.StopPlay();
               }
            }
            function rewind() {
               if (document.demo.IsPlaying()) {
                  document.demo.StopPlay();
               }
               document.demo.Rewind();
            }
         //-->
      </script>
   </head>

   <body>
      <embed id = "demo" name = "demo"
         src = "http://www.amrood.com/games/kumite.swf"
         width = "318" height = "300" play = "false" loop = "false"
         pluginspage = "http://www.macromedia.com/go/getflashplayer"
         swliveconnect = "true">

      <form name = "form" id = "form" action = "#" method = "get">
         <input type = "button" value = "Start" onclick = "play();" />
         <input type = "button" value = "Stop" onclick = "stop();" />
         <input type = "button" value = "Rewind" onclick = "rewind();" />
      </form>
   </body>
</html>

Output

如果你使用的是Mozilla、Firefox或Netscape,那么:

JavaScript - Debugging

开发者经常在编码时会犯错误。程序或脚本中的错误称为` bug `。

查找和修复错误的过程被称为` debugging `,是开发过程中的正常部分。本部分涵盖了可以帮助你完成调试任务的工具和技术。

Error Messages in IE

追踪错误的最基本的方法是启用浏览器中的错误信息。默认情况下,当页面上发生错误时,Internet Explorer会在状态栏中显示一个错误图标。

error icon

双击此图标,你将进入一个显示有关所发生具体错误的信息的对话框。

由于此图标很容易被人忽略,因此Internet Explorer为你提供了在发生错误时自动显示“错误”对话框的选项。

要启用此选项,请选中` Tools → Internet Options → Advanced tab. ,然后最终选中 "Display a Notification About Every Script Error" `框,如下所示:

internet options

Error Messages in Firefox or Mozilla

像 Firefox、Netscape 以及 Mozilla 等其他浏览器会将错误信息发送到一个名为 JavaScript ConsoleError Consol 的特殊窗口。要查看控制台,请选择 Tools → Error Consol or Web Development

不幸的是,由于这些浏览器在发生错误时不会给出任何视觉指示,因此你必须保持控制台打开,并在脚本执行时注意错误。

error console

Error Notifications

控制台中显示的或通过 Internet Explorer 对话框显示的错误通知都是语法和运行时错误造成的。这些错误通知包含发生错误的行号。

如果你使用的是 Firefox,则可以单击错误控制台中提供的错误以转到脚本中出现错误的确切行。

How to debug a Script

有多种方法可以调试 JavaScript −

Use a JavaScript Validator

检查 JavaScript 代码中是否存在异常错误的一种方法是通过程序来运行它,以确保它是有效的,并且它遵循该语言的官方语法规则。这些程序称为 validating parsers 或简称 validators ,通常附带商业 HTML 和 JavaScript 编辑器。

JavaScript 最方便的验证器是 Douglas Crockford 的 JavaScript Lint,该验证器可以在 Douglas Crockford’s JavaScript Lint 免费获得。

只需访问该网页,将 JavaScript(仅 JavaScript)代码粘贴到提供的文本区域中,然后单击 jslint 按钮。此程序将解析 JavaScript 代码,确保所有变量和函数定义都遵循正确的语法。它还将检查 JavaScript 语句,例如 if 和 while, 以确保它们也遵循正确的格式

Add Debugging Code to Your Programs

你可以在程序中使用 alert()document.write() 方法来调试代码。例如,你可以编写类似以下内容的东西 −

var debugging = true;
var whichImage = "widget";

if( debugging )
   alert( "Calls swapImage() with argument: " + whichImage );
   var swapStatus = swapImage( whichImage );

if( debugging )
   alert( "Exits swapImage() with swapStatus=" + swapStatus );

通过检查 alert() 出现的顺序和内容,你可以非常容易地检查程序的运行状况。

Use a JavaScript Debugger

调试器是一种将脚本执行的所有方面置于程序员控制之下的应用程序。调试器通过允许你检查和设置值以及控制执行流的接口,提供了对脚本状态的精细控制。

将脚本加载到调试器中后,可以一次运行一行,或者指示在某些断点处停止。中止执行后,程序员可以检查脚本及其变量的状态,以确定是否有问题。你还可以观察变量的值的变化。

最新的 Mozilla JavaScript 调试器(代号 Venkman)适用于 Mozilla 和 Netscape 浏览器,可以在链接:https://www.hacksrus.com/ ginda/venkman[http://www.hacksrus.com/ ginda/venkman] 下载

Useful Tips for Developers

你可以记住以下提示以减少脚本中的错误数量并简化调试过程 −

  1. 充分利用 comments 。注释使你可以解释编写脚本的方式以及解释特别困难的代码部分。

  2. 始终使用 indentation 使代码易于阅读。缩进语句还可以使你更容易匹配开始和结束标记、大括号以及其他 HTML 和脚本元素。

  3. 编写 modular code 。尽可能将语句分组到函数中。函数允许你对相关语句进行分组,并以最小的工作量测试和重用代码部分。

  4. 给变量和函数命名时保持一致。尝试使用足够长的有意义的名称,并描述变量的内容或函数的目的。

  5. 给变量和函数命名时使用一致的语法。换句话说,保持它们全部小写或全部大写;如果你喜欢骆驼命名法,请始终如一地使用它。

  6. Test long scripts 的模块化方式。换句话说,不要在测试它任何部分之前尝试编写整个脚本。编写一部分并让它在添加下一部分代码之前起作用。

  7. 使用 descriptive variable and function names 并且避免使用单字符名称。

  8. Watch your quotation marks 。记住,引号成对地用于字符串周围,并且两个引号都必须是同一种样式(单引号或双引号)。

  9. Watch your equal signs 。您不应为比较目的使用单个 =。

  10. 使用 var 关键字声明 variables explicitly

JavaScript - Image Map

你可以使用 JavaScript 来创建客户端图像映射。客户端图像映射是由 <img /> 标记的 usemap 属性启用的,并由特殊的 <map> 和 <area> 扩展标记定义。

构成映射的图像通过 <img /> 元素插入页面与平时一样,除了它带有称为 usemap 的额外属性。usemap 属性的值是 <map> 元素上 name 属性值,你即将遇到,前面有一个井号或磅号。

<map> 元素实际创建图像的映射,通常紧跟在 <img /> 元素之后。它充当 <area /> 元素的容器,<area /> 元素实际定义可点击热点。<map> 元素只有一个属性, name 属性,它是标识映射的名称。这是 <img /> 元素知道要使用哪个 <map> 元素的方式。

<area> 元素指定形状和坐标,它们定义每个可点击热点的边界。

以下代码结合了图像映射和 JavaScript,当鼠标移动到图像的不同部分时,在文本框中生成一条消息。

<html>
   <head>
      <title>Using JavaScript Image Map</title>

      <script type = "text/javascript">
         <!--
            function showTutorial(name) {
               document.myform.stage.value = name
            }
         //-->
      </script>
   </head>

   <body>
      <form name = "myform">
         <input type = "text" name = "stage" size = "20" />
      </form>

      <!-- Create  Mappings -->
      <img src = "/images/usemap.gif" alt = "HTML Map" border = "0" usemap = "#tutorials"/>

      <map name = "tutorials">
         <area shape="poly"
            coords = "74,0,113,29,98,72,52,72,38,27"
            href = "/perl/index.htm" alt = "Perl Tutorial"
            target = "_self"
            onMouseOver = "showTutorial('perl')"
            onMouseOut = "showTutorial('')"/>

         <area shape = "rect"
            coords = "22,83,126,125"
            href = "/html/index.htm" alt = "HTML Tutorial"
            target = "_self"
            onMouseOver = "showTutorial('html')"
            onMouseOut = "showTutorial('')"/>

         <area shape = "circle"
            coords = "73,168,32"
            href = "/php/index.htm" alt = "PHP Tutorial"
            target = "_self"
            onMouseOver = "showTutorial('php')"
            onMouseOut = "showTutorial('')"/>
      </map>
   </body>
</html>

Output

你可以将鼠标光标放在图像对象上感受映射概念。

JavaScript - Browsers Compatibility

为了以预期的方式处理每个浏览器,重要的是了解不同浏览器之间的差异。因此,了解您的网页正在哪个浏览器中运行非常重要。

用内置 navigator 对象获取您的网页当前正在运行的浏览器信息。

Navigator Properties

有一些与 Navigator 相关的属性,您可以在您的网页中使用。以下是每个属性的名称和说明。

Sr.No.

Property & Description

1

appCodeName 此属性是一个字符串,包含浏览器的代码名称,Netscape 的 Netscape 和 Internet Explorer 的 Microsoft Internet Explorer。

2

appVersion 此属性是一个字符串,包含浏览器的版本以及其他有用的信息,例如其语言和兼容性。

3

language 此属性包含浏览器使用的该语言的两个字母缩写。仅限 Netscape。

4

mimTypes[] 此属性是一个数组,其中包含客户端支持的所有 MIME 类型。仅限 Netscape。

5

platform[] 此属性是一个字符串,其中包含编译浏览器的平台。“Win32”适用于 32 位 Windows 操作系统。

6

plugins[] 此属性是一个数组,其中包含已安装在客户端上的所有插件。仅限 Netscape。

7

userAgent[] 此属性是一个字符串,其中包含浏览器的代码名称和版本。此值发送到源服务器来标识客户端。

Navigator Methods

有一些特定的 Navigator 方法。以下是它们名称和说明的列表。

Sr.No.

Description

1

javaEnabled() 此方法确定客户端中是否启用了 JavaScript。如果启用了 JavaScript,此方法返回 true;否则,它返回 false。

2

plugings.refresh 此方法使新安装的插件可用,并使用所有新插件名称填充插件数组。仅限 Netscape。

3

preference(name,value) 此方法允许已签名的脚本获取并设置一些 Netscape 首选项。如果省略了第二个参数,此方法将返回指定首选项的值;否则,它会设置此值。仅限 Netscape。

4

taintEnabled() 如果已启用数据污染,此方法返回真;否则返回假。

Browser Detection

有一个简单的 JavaScript,它可以用来找出浏览器的名称,然后可以向用户提供相应 HTML 页面。

<html>
   <head>
      <title>Browser Detection Example</title>
   </head>

   <body>
      <script type = "text/javascript">
         <!--
            var userAgent   = navigator.userAgent;
            var opera       = (userAgent.indexOf('Opera') != -1);
            var ie          = (userAgent.indexOf('MSIE') != -1);
            var gecko       = (userAgent.indexOf('Gecko') != -1);
            var netscape    = (userAgent.indexOf('Mozilla') != -1);
            var version     = navigator.appVersion;

            if (opera) {
               document.write("Opera based browser");
               // Keep your opera specific URL here.
            } else if (gecko) {
               document.write("Mozilla based browser");
               // Keep your gecko specific URL here.
            } else if (ie) {
               document.write("IE based browser");
               // Keep your IE specific URL here.
            } else if (netscape) {
               document.write("Netscape based browser");
               // Keep your Netscape specific URL here.
            } else {
               document.write("Unknown browser");
            }

            // You can include version to along with any above condition.
            document.write("<br /> Browser version info : " + version );
         //-->
      </script>
   </body>
</html>

Output