Javascript 简明教程
JavaScript - Overview
What is JavaScript ?
JavaScript 是一种动态计算机编程语言。它很轻量,最常用作网页的一部分,其实现允许客户端脚本与用户进行交互并制作动态页面。它是一种具有面向对象功能的解释性编程语言。
JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side script to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities.
JavaScript 最初被称为 LiveScript, ,但 Netscape 将其名称改为 JavaScript,可能是因为 Java 产生的激昂。JavaScript 于 1995 年首次在 Netscape 2.0 中以 LiveScript 的名称出现。该语言的通用核心已嵌入 Netscape、Internet Explorer 和其他网络浏览器中。
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.
ECMA-262 Specification 定义了核心 JavaScript 语言的标准版本。
The ECMA-262 Specification defined a standard version of the core JavaScript language.
-
JavaScript is a lightweight, interpreted programming language.
-
Designed for creating network-centric applications.
-
Complementary to and integrated with Java.
-
Complementary to and integrated with HTML.
-
Open and cross-platform
Client-Side JavaScript
客户端 JavaScript 是该语言最常用的形式。脚本应包含在 HTML 文档中或由其引用,这样浏览器才能解释该代码。
Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser.
这意味着一个网页不必是静态 HTML,但可以包含与用户交互、控制浏览器和动态创建 HTML 内容的程序。
It means that a web page need not be a static HTML, but can include programs that interact with the user, control the browser, and dynamically create HTML content.
JavaScript 客户端机制比传统的 CGI 服务器端脚本提供了许多优势。例如,你可以使用 JavaScript 来检查用户是否在表单字段中输入了有效的电子邮件地址。
The JavaScript client-side mechanism provides many advantages over traditional CGI server-side scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in a form field.
JavaScript 代码在用户提交表单时执行,并且只有在所有条目有效时,才会提交给 Web 服务器。
The JavaScript code is executed when the user submits the form, and only if all the entries are valid, they would be submitted to the Web Server.
JavaScript 可用于捕获用户发起的事件,例如按钮点击、链接导航以及用户显式或隐式发起的其他操作。
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
使用 JavaScript 的优点为 −
The merits of using JavaScript are −
-
Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
-
Immediate feedback to the visitors − They don’t have to wait for a page reload to see if they have forgotten to enter something.
-
Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
-
Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript
我们不能将 JavaScript 当作一门成熟的编程语言。它缺少以下重要特性 −
We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features −
-
Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.
-
JavaScript cannot be used for networking applications because there is no such support available.
-
JavaScript doesn’t have any multi-threading or multiprocessor capabilities.
再说一遍,JavaScript 是一种轻量级解释型编程语言,让你可以将交互性融入到原本静态的 HTML 页面中。
Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into otherwise static HTML pages.
JavaScript Development Tools
JavaScript 的主要优点之一在于它不需要昂贵的开发工具。你可以从简单的文本编辑器(如记事本)开始。由于它是一种在 Web 浏览器上下文中解释的语言,你甚至不需要购买编译器。
One of major strengths of JavaScript is that it does not require expensive development tools. You can start with a simple text editor such as Notepad. Since it is an interpreted language inside the context of a web browser, you don’t even need to buy a compiler.
为了让我们的生活更轻松,各种供应商推出了非常不错的 JavaScript 编辑工具。其中一些工具如下 −
To make our life simpler, various vendors have come up with very nice JavaScript editing tools. Some of them are listed here −
-
Microsoft FrontPage − Microsoft has developed a popular HTML editor called FrontPage. FrontPage also provides web developers with a number of JavaScript tools to assist in the creation of interactive websites.
-
Macromedia Dreamweaver MX − Macromedia Dreamweaver MX is a very popular HTML and JavaScript editor in the professional web development crowd. It provides several handy prebuilt JavaScript components, integrates well with databases, and conforms to new standards such as XHTML and XML.
-
Macromedia HomeSite 5 − HomeSite 5 is a well-liked HTML and JavaScript editor from Macromedia that can be used to manage personal websites effectively.
Where is JavaScript Today ?
ECMAScript 第 5 版标准将是时隔四年发布的首次更新。JavaScript 2.0 符合 ECMAScript 标准第 5 版,而两者之间的区别非常微小。
The ECMAScript Edition 5 standard will be the first update to be released in over four years. JavaScript 2.0 conforms to Edition 5 of the ECMAScript standard, and the difference between the two is extremely minor.
JavaScript 2.0 的规范可以在以下网站上找到: https://www-archive.mozilla.org/js/language/js20-2002-04/
The specification for JavaScript 2.0 can be found on the following site: https://www-archive.mozilla.org/js/language/js20-2002-04/
如今,Netscape 的 JavaScript 和 Microsoft 的 JScript 均符合 ECMAScript 标准,虽然这两种语言仍然支持不属于该标准的功能。
Today, Netscape’s JavaScript and Microsoft’s JScript conform to the ECMAScript standard, although both the languages still support the features that are not a part of the standard.
JavaScript - Syntax
JavaScript 可使用放置在网页 <script>… </script> HTML 标记中的 JavaScript 语句来实现。
JavaScript can be implemented using JavaScript statements that are placed within the <script>… </script> HTML tags in a web page.
你可以在网页中的任何位置放置包含 JavaScript 的 <script> 标记,但通常建议你将它包含在 <head> 标记中。
You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags.
<script> 标记警示浏览器程序开始解读这些标记之间的所有文本作为脚本。你的 JavaScript 的一个简单语法将如下所示。
The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
script 标记有两个重要的属性 −
The script tag takes two important attributes −
-
Language − This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.
-
Type − This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript".
因此,你的 JavaScript 代码段看起来像 −
So your JavaScript segment will look like −
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>
Your First JavaScript Code
让我们举一个打印“Hello World”的示例。我们添加了一个可选的 HTML 注释,该注释围绕我们的 JavaScript 代码。这是为了将我们的代码保存在不支持 JavaScript 的浏览器中。注释以“//-→”结尾。此处,“//”表示 JavaScript 中的注释,因此我们添加了该注释,以防止浏览器将 HTML 注释的结尾读取为 JavaScript 代码的一部分。接下来,我们调用一个函数 document.write ,该函数将一个字符串写入我们的 HTML 文档。
Let us take a sample example to print out "Hello World". We added an optional HTML comment that surrounds our JavaScript code. This is to save our code from a browser that does not support JavaScript. The comment ends with a "//-→". Here "//" signifies a comment in JavaScript, so we add that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code. Next, we call a function document.write which writes a string into our HTML document.
可以使用此函数来编写文本、HTML 或两者。请查看以下代码。
This function can be used to write text, HTML, or both. Take a look at the following code.
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
此代码将产生以下结果 −
This code will produce the following result −
Hello World!
Whitespace and Line Breaks
JavaScript 忽略出现在 JavaScript 程序中空格、制表符和换行符。你可以在程序中自由地使用空格、制表符和换行符,并且可以自由地格式化和缩进你的程序,以一种清晰一致的方式,便于阅读和理解代码。
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.
Semicolons are Optional
JavaScript 中的简单语句通常后跟一个分号字符,就像它们在 C、C++ 和 Java 中一样。但是,JavaScript 允许你省略此分号,如果你的每个语句都位于单独的行中。例如,可以编写没有分号的以下代码。
Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your statements are placed on a separate line. For example, the following code could be written without semicolons.
<script language = "javascript" type = "text/javascript">
<!--
var1 = 10
var2 = 20
//-->
</script>
但是,如果按如下方式格式化为单行,则你必须使用分号 −
But when formatted in a single line as follows, you must use semicolons −
<script language = "javascript" type = "text/javascript">
<!--
var1 = 10; var2 = 20;
//-->
</script>
Note − 使用分号是一种良好的编程实践。
Note − It is a good programming practice to use semicolons.
Case Sensitivity
JavaScript 是一种区分大小写的语言。这意味着语言关键字、变量、函数名和任何其他标识符都必须始终采用一致的大小写字母输入。
JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.
所以在 JavaScript 中,标识符 Time 和 TIME 将传达不同的含义。
So the identifiers Time and TIME will convey different meanings in JavaScript.
NOTE − 在 JavaScript 中编写变量和函数名称时应小心。
NOTE − Care should be taken while writing variable and function names in JavaScript.
Comments in JavaScript
JavaScript 既支持 C 样式注释,也支持 C++ 样式注释,即 -
JavaScript supports both C-style and C++-style comments, Thus −
-
Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
-
Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
-
JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment.
-
The HTML comment closing sequence -→ is not recognized by JavaScript so it should be written as //-→.
Example
以下示例展示了如何在 JavaScript 中使用注释。
The following example shows how to use comments in 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 支持的过程。
All the modern browsers come with built-in support for JavaScript. Frequently, you may need to enable or disable this support manually. This chapter explains the procedure of enabling and disabling JavaScript support in your browsers: Internet Explorer, Firefox, chrome, and Opera.
JavaScript in Internet Explorer
以下是打开或关闭 Internet Explorer 中的 JavaScript 的简单步骤 −
Here are simple steps to turn on or turn off JavaScript in your Internet Explorer −
-
Follow Tools → Internet Options from the menu.
-
Select Security tab from the dialog box.
-
Click the Custom Level button.
-
Scroll down till you find Scripting option.
-
Select Enable radio button under Active scripting.
-
Finally click OK and come out
要在 Internet Explorer 中禁用 JavaScript 支持,你需要选择 Active scripting 下的 Disable 单选按钮。
To disable JavaScript support in your Internet Explorer, you need to select Disable radio button under Active scripting.
JavaScript in Firefox
以下是打开或关闭 Firefox 中 JavaScript 的步骤 −
Here are the steps to turn on or turn off JavaScript in Firefox −
-
Open a new tab → type about: config in the address bar.
-
Then you will find the warning dialog. Select I’ll be careful, I promise!
-
Then you will find the list of configure options in the browser.
-
In the search bar, type javascript.enabled.
-
There you will find the option to enable or disable javascript by right-clicking on the value of that option → select toggle.
如果 javascript.enabled 为真;单击 toogle 后会转换成假。如果禁用 JavaScript;单击切换后即可启用。
If javascript.enabled is true; it converts to false upon clicking toogle. If javascript is disabled; it gets enabled upon clicking toggle.
JavaScript in Chrome
以下是打开或关闭 Chrome 中 JavaScript 的步骤 −
Here are the steps to turn on or turn off JavaScript in Chrome −
-
Click the Chrome menu at the top right hand corner of your browser.
-
Select Settings.
-
Click Show advanced settings at the end of the page.
-
Under the Privacy section, click the Content settings button.
-
In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow all sites to run JavaScript (recommended)".
JavaScript in Opera
以下是打开或关闭 Opera 中 JavaScript 的步骤 −
Here are the steps to turn on or turn off JavaScript in Opera −
-
Follow Tools → Preferences from the menu.
-
Select Advanced option from the dialog box.
-
Select *Content * from the listed items.
-
Select Enable JavaScript checkbox.
-
Finally click OK and come out.
要禁用 Opera 中的 JavaScript 支持,你应该不选择 Enable JavaScript checkbox 。
To disable JavaScript support in your Opera, you should not select the Enable JavaScript checkbox.
Warning for Non-JavaScript Browsers
如果你必须使用 JavaScript 进行一些重要操作,那么可以使用 <noscript> 标记向用户显示一条警告消息。
If you have to do something important using JavaScript, then you can display a warning message to the user using <noscript> tags.
你可以像下面那样在脚本块之后立即添加一个 noscript 块:
You can add a noscript block immediately after the script block as follows −
<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> 中的信息会显示在屏幕上。
Now, if the user’s browser does not support JavaScript or JavaScript is not enabled, then the message from </noscript> will be displayed on the screen.
JavaScript - Placement in HTML File
允许在 HTML 文档中的任何位置包含 JavaScript 代码。然而,在 HTML 文件中包含 JavaScript 最推荐的方法如下:
There is a flexibility given to include JavaScript code anywhere in an HTML document. However the most preferred ways to include JavaScript in an HTML file are as follows −
-
Script in <head>…</head> section.
-
Script in <body>…</body> section.
-
Script in <body>…</body> and <head>…</head> sections.
-
Script in an external file and then include in <head>…</head> section.
在下一节中,我们将看到如何通过不同的方式将 JavaScript 放置在 HTML 文件中。
In the following section, we will see how we can place JavaScript in an HTML file in different ways.
JavaScript in <head>…</head> section
如果你想让一个脚本在某个事件上运行,比如用户在某处单击时,那么你将像下面那样把该脚本放在头部:
If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in the head as follows −
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
此代码将产生以下结果:
This code will produce the following results −
JavaScript in <body>…</body> section
如果你需要一个脚本在页面加载时运行,以便该脚本在页面中生成内容,那么该脚本会进入文档的 <body> 部分。在这种情况下,你不会使用 JavaScript 定义任何函数。看看下面的代码。
If you need a script to run as the page loads so that the script generates content in the page, then the script goes in the <body> portion of the document. In this case, you would not have any function defined using JavaScript. Take a look at the following code.
<html>
<head>
</head>
<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
此代码将产生以下结果:
This code will produce the following results −
JavaScript in <body> and <head> Sections
你可以像下面那样把 JavaScript 代码放在 <head> 和 <body> 部分:
You can put your JavaScript code in <head> and <body> section altogether as follows −
<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>
此代码将产生以下结果 −
This code will produce the following result −
JavaScript in External File
当你逐渐更深入地使用 JavaScript,你会发现有些情况下你正在某个网站的多页面上重复使用相同的 JavaScript 代码。
As you begin to work more extensively with JavaScript, you will be likely to find that there are cases where you are reusing identical JavaScript code on multiple pages of a site.
你不一定要在多个 HTML 文件中维护相同的代码。 script 标记提供了一个机制,允许你在一个外部文件中存储 JavaScript,然后将其包含到你的 HTML 文件中。
You are not restricted to be maintaining identical code in multiple HTML files. The script tag provides a mechanism to allow you to store JavaScript in an external file and then include it into your HTML files.
这里有一个示例,展示了如何使用 script 标记及其 src 属性在 HTML 代码中包含一个外部 JavaScript 文件。
Here is an example to show how you can include an external JavaScript file in your HTML code using script tag and its src attribute.
<html>
<head>
<script type = "text/javascript" src = "filename.js" ></script>
</head>
<body>
.......
</body>
</html>
要从外部文件源使用 JavaScript,你需要在扩展名为 “.js” 的简单文本文件中编写所有 JavaScript 源代码,然后像上面那样包含该文件。
To use JavaScript from an external file source, you need to write all your JavaScript source code in a simple text file with the extension ".js" and then include that file as shown above.
例如,你可以将以下内容保存在 filename.js 文件中,然后你可以在包含 filename.js 文件后在你的 HTML 文件中使用 sayHello 函数。
For example, you can keep the following content in filename.js file and then you can use sayHello function in your HTML file after including the filename.js file.
function sayHello() {
alert("Hello World")
}
JavaScript - Variables
JavaScript Datatypes
编程语言最重要的特性之一是它支持的数据类型集。这些类型的值可以在编程语言中表示和操纵。
One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.
JavaScript 允许你使用三种基本数据类型:
JavaScript allows you to work with three primitive data types −
-
Numbers, eg. 123, 120.50 etc.
-
Strings of text e.g. "This text string" etc.
-
Boolean e.g. true or false.
JavaScript 也定义了两个简单的数据类型, null 和 undefined, ,每个只定义单个值。除开这些原始数据类型外,JavaScript 还支持称为 object 的复合数据类型。我们将在单独的章节中详细介绍对象。
JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value. In addition to these primitive data types, JavaScript supports a composite data type known as object. We will cover objects in detail in a separate chapter.
Note − JavaScript 不区分整数和浮点数的值。JavaScript 中的所有数字都表示为浮点数。JavaScript 使用 IEEE 754 标准所定义的 64 位浮点格式表示数字。
Note − JavaScript does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.
JavaScript Variables
JavaScript 与许多其他编程语言类似,也有变量。可以将变量视为已命名的容器。你可以将数据放入这些容器中,然后通过命名容器来引用数据。
Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.
在 JavaScript 程序中使用变量之前,必须声明它。使用 var 关键字声明变量,如下所示:
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows.
<script type = "text/javascript">
<!--
var money;
var name;
//-->
</script>
你也可以使用相同的 var 关键字声明多个变量,如下所示:
You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
<!--
var money, name;
//-->
</script>
将值存储在变量中称为 variable initialization 。可以在创建变量时初始化变量,也可以在需要变量的稍后时间点进行初始化。
Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable.
例如,你可能会创建一个名为 money 的变量,稍后为其分配 2000.50 的值。对于另一个变量,你可以在初始化时分配值,如下所示:
For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable, you can assign a value at the time of initialization as follows.
<script type = "text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Note − 只在文档中任何变量名的生命周期中使用 var 关键字进行声明或初始化。你不应重新声明同一个变量两次。
Note − Use the var keyword only for declaration or initialization, once for the life of any variable name in a document. You should not re-declare same variable twice.
JavaScript 是一种 untyped 语言。这意味着 JavaScript 变量可以保存任何数据类型的值。与许多其他语言不同,你无需在变量声明期间告诉 JavaScript 变量将保存什么类型的变量。可以在程序执行期间更改变量的值类型,而 JavaScript 会自动处理它。
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don’t have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.
JavaScript Variable Scope
变量的范围是程序中定义它的区域。JavaScript 变量只有两个范围。
The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.
-
Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.
-
Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
在函数体中,局部变量优于具有相同名称的全局变量。如果使用全局变量的相同名称声明局部变量或函数参数,则可以有效隐藏全局变量。了解以下示例。
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example.
<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>
这会产生以下结果:
This produces the following result −
local
JavaScript Variable Names
在 JavaScript 中对变量命名时,请记住以下规则。
While naming your variables in JavaScript, keep the following rules in mind.
-
You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
-
JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
-
JavaScript variable names are case-sensitive. For example, Name and name are two different variables.
JavaScript Reserved Words
下表中提供了 JavaScript 中所有保留字的列表。它们不能用作 JavaScript 变量、函数、方法、循环标签或任何对象名。
A list of all the reserved words in JavaScript are given in the following table. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names.
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 支持以下类型的运算符。
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called the operator. JavaScript supports the following types of operators.
-
Arithmetic Operators
-
Comparison Operators
-
Logical (or Relational) Operators
-
Assignment Operators
-
Conditional (or ternary) Operators
我们逐一了解所有运算符。
Lets have a look on all operators one by one.
Arithmetic Operators
JavaScript 支持以下算术运算符 −
JavaScript supports the following arithmetic operators −
假设变量 A 为 10,变量 B 为 20,那么 −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No. |
Operator & Description |
1 |
+ (Addition) Adds two operands Ex: A + B will give 30 |
2 |
- (Subtraction) Subtracts the second operand from the first Ex: A - B will give -10 |
3 |
* (Multiplication) Multiply both operands Ex: A * B will give 200 |
4 |
/ (Division) Divide the numerator by the denominator Ex: B / A will give 2 |
5 |
% (Modulus) Outputs the remainder of an integer division Ex: B % A will give 0 |
6 |
* (Increment)* Increases an integer value by one Ex: A will give 11 |
7 |
-- (Decrement) Decreases an integer value by one Ex: A-- will give 9 |
Note − 加法运算符(+)对数字和字符串都可用。例如,"a" + 10 将得出 "a10"。
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
Example
以下代码演示如何在 JavaScript 中使用算术运算符。
The following code shows how to use arithmetic operators in 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>
Comparison Operators
JavaScript 支持以下比较运算符 −
JavaScript supports the following comparison operators −
假设变量 A 为 10,变量 B 为 20,那么 −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No. |
Operator & Description |
1 |
= = (Equal) Checks if the value of two operands are equal or not, if yes, then the condition becomes true. Ex: (A == B) is not true. |
2 |
!= (Not Equal) Checks if the value of two operands are equal or not, if the values are not equal, then the condition becomes true. Ex: (A != B) is true. |
3 |
> (Greater than) Checks if the value of the left operand is greater than the value of the right operand, if yes, then the condition becomes true. Ex: (A > B) is not true. |
4 |
< (Less than) Checks if the value of the left operand is less than the value of the right operand, if yes, then the condition becomes true. Ex: (A < B) is true. |
5 |
>= (Greater than or Equal to) Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then the condition becomes true. Ex: (A >= B) is not true. |
6 |
⇐ (Less than or Equal to) Checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the condition becomes true. Ex: (A ⇐ B) is true. |
Example
以下代码演示如何在 JavaScript 中使用比较运算符。
The following code shows how to use comparison operators in 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>
Logical Operators
JavaScript 支持以下逻辑运算符:
JavaScript supports the following logical operators −
假设变量 A 为 10,变量 B 为 20,那么 −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No. |
Operator & Description |
1 |
&& (Logical AND) If both the operands are non-zero, then the condition becomes true. Ex: (A && B) is true. |
2 |
* |
(Logical OR)* If any of the two operands are non-zero, then the condition becomes true. Ex: (A |
|
B) is true. |
|
3 |
! (Logical NOT) Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false. Ex: ! (A && B) is false. |
Example
尝试运行以下代码来学习如何在 JavaScript 中实现逻辑运算符。
Try the following code to learn how to implement Logical Operators in 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>
Bitwise Operators
JavaScript 支持以下按位运算符−
JavaScript supports the following bitwise operators −
假设变量 A 的值为 2,变量 B 的值为 3,则−
Assume variable A holds 2 and variable B holds 3, then −
Sr.No. |
Operator & Description |
1 |
& (Bitwise AND) It performs a Boolean AND operation on each bit of its integer arguments. Ex: (A & B) is 2. |
2 |
* |
(BitWise OR)* It performs a Boolean OR operation on each bit of its integer arguments. Ex: (A |
B) is 3. |
3 |
^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both. Ex: (A ^ B) is 1. |
4 |
~ (Bitwise Not) It is a unary operator and operates by reversing all the bits in the operand. Ex: (~B) is -4. |
5 |
<< (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and so on. Ex: (A << 1) is 4. |
6 |
>> (Right Shift) Binary Right Shift Operator. The left operand’s value is moved right by the number of bits specified by the right operand. Ex: (A >> 1) is 1. |
7 |
>>> (Right shift with Zero) This operator is just like the >> operator, except that the bits shifted in on the left are always zero. Ex: (A >>> 1) is 1. |
Example
尝试运行以下代码在 JavaScript 中实现按位运算符。
Try the following code to implement Bitwise operator in 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 支持以下赋值运算符 −
JavaScript supports the following assignment operators −
Sr.No. |
Operator & Description |
1 |
= (Simple Assignment ) Assigns values from the right side operand to the left side operand Ex: C = A + B will assign the value of A + B into C |
2 |
+= (Add and Assignment) It adds the right operand to the left operand and assigns the result to the left operand. Ex: C += A is equivalent to C = C + A |
3 |
−= (Subtract and Assignment) It subtracts the right operand from the left operand and assigns the result to the left operand. Ex: C -= A is equivalent to C = C - A |
4 |
*= (Multiply and Assignment) It multiplies the right operand with the left operand and assigns the result to the left operand. Ex: C *= A is equivalent to C = C * A |
5 |
/= (Divide and Assignment) It divides the left operand with the right operand and assigns the result to the left operand. Ex: C /= A is equivalent to C = C / A |
6 |
%= (Modules and Assignment) It takes modulus using two operands and assigns the result to the left operand. Ex: C %= A is equivalent to C = C % A |
Note − 同样的逻辑适用于按位运算符,所以它们将变成 <⇐, >>=, >>=, &=, |= 和 ^=.
Note − Same logic applies to Bitwise operators so they will become like <⇐, >>=, >>=, &=, |= and ^=.
Example
尝试使用以下代码在 JavaScript 中实现赋值运算符。
Try the following code to implement assignment operator in 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>
Miscellaneous Operator
我们这里将讨论两个非常实用的 JavaScript 运算符: conditional operator (? :) 和 typeof operator .
We will discuss two operators here that are quite useful in JavaScript: the conditional operator (? :) and the typeof operator.
Conditional Operator (? :)
条件运算符首先对某个表达式求值为真或假,然后根据求值的结果执行两个给定语句中的一个。
The conditional operator first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.
Sr.No. |
Operator and Description |
1 |
? : (Conditional ) If Condition is true? Then value X : Otherwise value Y |
Example
尝试使用以下代码了解条件运算符在 JavaScript 中是如何工作的。
Try the following code to understand how the Conditional Operator works in 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>
typeof Operator
typeof 运算符是一个一元运算符,它放在单个操作数之前,该操作数可以是任何类型。它的值为一个字符串,表示该操作数的数据类型。
The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.
如果操作数是数字、字符串或布尔值,typeof 运算符将求值为“number”、“string”或“boolean”,并根据求值结果返回真或假。
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation.
以下是 typeof 操作符的返回值列表。
Here is a list of the return values for the typeof Operator.
Type |
String Returned by typeof |
Number |
"number" |
String |
"string" |
Boolean |
"boolean" |
Object |
"object" |
Function |
"function" |
Undefined |
"undefined" |
Null |
"object" |
Example
以下代码显示了如何实现 typeof 运算符。
The following code shows how to implement typeof operator.
<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>
JavaScript - if…else Statement
在编写程序时,可能会出现需要采用给定路径集中某个路径的情况。在这种情况中,您需要使用条件语句,让您的程序做出正确的决策并执行正确的操作。
While writing a program, there may be a situation when you need to adopt one out of a given set of paths. In such cases, you need to use conditional statements that allow your program to make correct decisions and perform right actions.
JavaScript 支持条件语句,用于根据不同的条件执行不同的操作。这里我们将解释 if..else 语句。
JavaScript supports conditional statements which are used to perform different actions based on different conditions. Here we will explain the if..else statement.
Flow Chart of if-else
以下流程图显示了 if-else 语句的工作方式。
The following flow chart shows how the if-else statement works.
JavaScript 支持以下形式的 if..else 语句 −
JavaScript supports the following forms of if..else statement −
-
if statement
-
if…else statement
-
if…else if… statement.
if statement
if 语句是 JavaScript 中用于做出决定和有条件执行语句的基本控制语句。
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.
Syntax
基本 if 语句的语法如下 −
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
这里计算一个 JavaScript 表达式。如果计算结果为真,则执行给定的语句。如果该表达式为假,则不执行任何语句。在做出决策时,您大多数时候会使用比较运算符。
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are executed. If the expression is false, then no statement would be not executed. Most of the times, you will use comparison operators while making decisions.
Example
尝试使用以下示例了解 if 语句的工作方式。
Try the following example to understand how the if statement works.
<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>
if…else statement
'if…else' 语句是控制语句的另一种形式,允许 JavaScript 以更受控的方式执行语句。
The 'if…else' statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way.
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 块中的给定语句。
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block are executed.
Example
尝试运行以下代码,以了解如何在 JavaScript 中实现 if-else 语句。
Try the following code to learn how to implement an if-else statement in JavaScript.
<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>
if…else if… statement
if…else if… 语句是 if…else 的高级形式,它允许 JavaScript 根据多个条件做出正确的决策。
The if…else if… statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions.
Syntax
if-else-if 语句的语法如下所示:
The syntax of an if-else-if statement is as follows −
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 块。
There is nothing special about this code. It is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed.
Example
尝试运行以下代码,以了解如何在 JavaScript 中实现 if-else-if 语句。
Try the following code to learn how to implement an if-else-if statement in JavaScript.
<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>
JavaScript - Switch Case
您可以使用多个 if…else…if 语句(如上一章节中所示)执行多项分支。但这并不总是最佳解决方案,尤其是在所有分支都依赖于单个变量的值时。
You can use multiple if…else…if statements, as in the previous chapter, to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable.
从 JavaScript 1.2 开始,您可以使用 switch 语句处理这种情况,它的效率高于重复的 if…else if 语句。
Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation, and it does so more efficiently than repeated if…else if statements.
Flow Chart
下方的流程图说明了 switch-case 语句的运行方式:
The following flow chart explains a switch-case statement works.
Syntax
switch 语句的目标是给出一个需要计算的表达式和根据表达式的值执行的多个不同的语句。解释器会将每个 case 与表达式的值进行对比,直到找到匹配值。如果没有匹配值,则会使用 default 条件。
The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.
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 中执行每条语句。
The break statements indicate the end of a particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases.
我们将在 Loop Control 章节中说明 break 语句。
We will explain break statement in Loop Control chapter.
Example
尝试执行以下示例,以实现 switch-case 语句。
Try the following example to implement switch-case statement.
<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 语句。
Break statements play a major role in switch-case statements. Try the following code that uses switch-case statement without any break statement.
<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>
JavaScript - While Loops
在编写程序时,您可能会遇到需要一遍又一遍地执行某个操作的情况。在这种情况下,您需要编写循环语句,以减少代码行数。
While writing a program, you may encounter a situation where you need to perform an action over and over again. In such situations, you would need to write loop statements to reduce the number of lines.
JavaScript 支持所有必要的循环,可简化编程压力。
JavaScript supports all the necessary loops to ease down the pressure of programming.
The while Loop
JavaScript 中最基本的循环是 while 循环,将在本章节中探讨该循环。 while 循环的目的是只要某个 expression 为真,就重复执行某条语句或代码块。一旦该表达式的值变为 false, ,循环将终止。
The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates.
Syntax
while loop 在 JavaScript 中的语法如下所示 −
The syntax of while loop in JavaScript is as follows −
while (expression) {
Statement(s) to be executed if expression is true
}
Example
尝试运行以下示例,以实现 while 循环。
Try the following example to implement while loop.
<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>
The do…while Loop
do…while 循环与 while 循环类似,区别在于条件检查发生在循环结尾。这意味着循环将始终至少执行一次,即使条件为 false 。
The do…while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.
Syntax
JavaScript 中 do-while 循环的语法如下 −
The syntax for do-while loop in JavaScript is as follows −
do {
Statement(s) to be executed;
} while (expression);
Note - 不要错过 do…while 循环结尾处所用的分号。
Note − Don’t miss the semicolon used at the end of the do…while loop.
Example
通过以下示例来学习如何在 JavaScript 中实现一个 do-while 循环。
Try the following example to learn how to implement a do-while loop in JavaScript.
<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>
JavaScript - For Loop
for 循环是最紧凑的循环形式。它包括以下三个重要部分 -
The 'for' loop is the most compact form of looping. It includes the following three important parts −
-
The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
-
The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
-
The iteration statement where you can increase or decrease your counter.
你可以用分号分隔三个部分,把它们放在一行中。
You can put all the three parts in a single line separated by semicolons.
Flow Chart
for 循环在 JavaScript 中的流程图如下 −
The flow chart of a for loop in JavaScript would be as follows −
Syntax
for 循环在 JavaScript 中的语法如下 −
The syntax of for loop is JavaScript is as follows −
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}
Example
通过以下示例来了解 for 循环在 JavaScript 中的工作原理。
Try the following example to learn how a for loop works in 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>
JavaScript for…in loop
for…in 循环用于循环遍历对象的属性。因为我们还没有讨论过对象,所以你可能对此循环感到不适应。但一旦你理解 JavaScript 中对象的运行方式,你将发现这个循环很有用。
The for…in loop is used to loop through an object’s properties. As we have not discussed Objects yet, you may not feel comfortable with this loop. But once you understand how objects behave in JavaScript, you will find this loop very useful.
Syntax
for (variablename in object) {
statement or block to execute
}
在每次迭代中, object 中的一个属性被分配给 variablename ,此循环将持续到对象的全部属性都被穷尽。
In each iteration, one property from object is assigned to variablename and this loop continues till all the properties of the object are exhausted.
Example
通过以下示例来实现“for-in”循环。它打印 web 浏览器的 Navigator 对象。
Try the following example to implement ‘for-in’ loop. It prints the web browser’s Navigator object.
<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 provides full control to handle loops and switch statements. There may be a situation when you need to come out of a loop without reaching its bottom. There may also be a situation when you want to skip a part of your code block and start the next iteration of the loop.
为了处理所有此类情况,JavaScript 提供了 break 和 continue 语句。这些语句分别用于立即退出任何循环或开始任何循环的下一个迭代。
To handle all such situations, JavaScript provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively.
The break Statement
break 语句与 switch 语句一起被简要介绍过,用于提前退出循环,从封闭的花括号中跳出。
The break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces.
Example
以下示例说明了使用 break 语句与 while 循环。注意循环如何一到达 5 就提前退出,并且到达作为结束花括号下方 document.write (..) 语句 -
The following example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early once x reaches 5 and reaches to document.write (..) statement just below to the closing curly brace −
<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>
The continue Statement
continue 语句告诉解释器立即开始循环的下一个迭代并跳过剩余的代码块。当遇到 continue 语句时,程序流程立即移动到循环检查表达式,如果条件仍然为真,则它开始下一个迭代,否则控件将退出循环。
The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop.
Example
此示例说明了将 continue 语句与while循环一起使用的情况。注意,当 x 变量中持有的索引达到5时,如何使用 continue 语句跳过打印 −
This example illustrates the use of a continue statement with a while loop. Notice how the continue statement is used to skip printing when the index held in variable x reaches 5 −
<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>
Using Labels to Control the Flow
从JavaScript 1.2开始,可以使用标签和 break 和 continue 来更精确地控制流。 label 只是表示符,后跟冒号(:),可以用到语句或代码块中。我们将看到两个不同的示例以理解如何将标签与break和continue结合使用。
Starting from JavaScript 1.2, a label can be used with break and continue to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. We will see two different examples to understand how to use labels with break and continue.
Note - 不允许在 ‘continue’ 或 ‘break’ 语句及其标签名之间换行。而且,标签名和关联循环之间也不应该有任何其他语句。
Note − Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label name. Also, there should not be any other statement in between a label name and associated loop.
尝试以下两个示例以更好地理解标签。
Try the following two examples for a better understanding of Labels.
Example 1
以下示例演示如何使用 break 语句实现标签。
The following example shows how to implement Label with a break statement.
<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>
JavaScript - Functions
函数是一组可重用代码,可以在程序中的任何地方调用它。这就消除了反复编写相同代码的需要。它帮助程序员编写模块化代码。函数允许程序员将一个大型程序划分为一些小而易于管理的函数。
A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions.
与其他高级编程语言一样,JavaScript 也支持使用函数编写模块化代码所需的一切功能。你一定在前面的章节中看到过 alert() 和 write() 这样的函数。我们一直在反复使用这些函数,但是它们只在核心 JavaScript 中被编写过一次。
Like any other advanced programming language, JavaScript also supports all the features necessary to write modular code using functions. You must have seen functions like alert() and write() in the earlier chapters. We were using these functions again and again, but they had been written in core JavaScript only once.
JavaScript 也允许我们编写自己的函数。本节介绍如何在 JavaScript 中编写自己的函数。
JavaScript allows us to write our own functions as well. This section explains how to write your own functions in JavaScript.
Function Definition
在使用函数之前,我们需要定义它。在 JavaScript 中定义函数最常见的方式是使用 function 关键字,后面跟一个唯一函数名、一个可能为空的参数列表以及花括号括起来的一个语句块。
Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.
Calling a Function
要在脚本中稍后的某个地方调用某个函数,您只需按照以下代码所示编写该函数的名称。
To invoke a function somewhere later in the script, you would simply need to write the name of that function as shown in the following code.
<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>
Function Parameters
到目前为止,我们已经看到了没有参数的函数。但在调用函数时,可以使用一个功能来传递不同参数。这些已传递参数可以在函数中捕获,并且可以对这些参数执行任何操作。函数可以接受多个以逗号分隔的参数。
Till now, we have seen functions without parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma.
Example
尝试以下示例。我们在这里修改了我们的 sayHello 函数。现在,它使用两个参数。
Try the following example. We have modified our sayHello function here. Now it takes two parameters.
<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>
The return Statement
JavaScript 函数可以具有可选的 return 语句。如果您想从函数中返回值,则需要此语句。此语句应该是函数中的最后一个语句。
A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function.
例如,您可以在函数中传递两个数字,然后让该函数在您的调用程序中返回它们的乘积。
For example, you can pass two numbers in a function and then you can expect the function to return their multiplication in your calling program.
Example
尝试以下示例。它定义了一个函数,该函数采用两个参数,并在将结果返回调用程序中之前将它们连接起来。
Try the following example. It defines a function that takes two parameters and concatenates them before returning the resultant in the calling program.
<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>
JavaScript - Events
What is an Event ?
JavaScript 与 HTML 的交互是通过用户或浏览器操作页面时发生的事件进行处理的。
JavaScript’s interaction with HTML is handled through events that occur when the user or the browser manipulates a page.
当页面加载时,这被称为一个事件。当用户单击一个按钮时,该单击也是一个事件。其他示例包括诸如按任意键、关闭窗口、调整窗口大小等事件。
When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.
开发者可以使用这些事件来执行 JavaScript 编码响应,这会导致按钮关闭窗口、向用户显示消息、验证数据以及几乎任何其他类型的可想而知响应。
Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable.
事件是文档对象模型 (DOM) 级别 3 的一部分,每个 HTML 元素都包含一组可以触发 JavaScript 代码的事件。
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code.
请浏览这个小程序教程以更好地理解 HTML Event Reference 。在这里,我们将看到几个示例来理解事件和 JavaScript 之间的关系 -
Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see a few examples to understand a relation between Event and JavaScript −
onclick Event Type
这是用户单击其鼠标左键时发生的最常用事件类型。您可以针对此事件类型放置您的验证、警告等操作。
This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type.
Example
尝试以下示例。
Try the following 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>
onsubmit Event Type
onsubmit 是您尝试提交表单时发生的事件。您可以针对此事件类型放置您的表单验证。
onsubmit is an event that occurs when you try to submit a form. You can put your form validation against this event type.
Example
以下示例显示了如何使用 onsubmit。我们在此准备向 web 服务器提交表单数据之前调用一个 validate() 函数。如果 validate() 函数返回 true,则表单将被提交,否则它将不提交数据。
The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data.
尝试以下示例。
Try the following example.
<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 在您将鼠标移出该元素时触发。尝试以下示例。
These two event types will help you create nice effects with images or even with text as well. The onmouseover event triggers when you bring your mouse over any element and the onmouseout triggers when you move your mouse out from that element. Try the following example.
<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>
HTML 5 Standard Events
在此处列出标准的 HTML 5 事件以供您参考。此处脚本指示针对该事件执行的 Javascript 函数。
The standard HTML 5 events are listed here for your reference. Here script indicates a Javascript function to be executed against that event.
Attribute |
Value |
Description |
Offline |
script |
Triggers when the document goes offline |
Onabort |
script |
Triggers on an abort event |
onafterprint |
script |
Triggers after the document is printed |
onbeforeonload |
script |
Triggers before the document loads |
onbeforeprint |
script |
Triggers before the document is printed |
onblur |
script |
Triggers when the window loses focus |
oncanplay |
script |
Triggers when media can start play, but might has to stop for buffering |
oncanplaythrough |
script |
Triggers when media can be played to the end, without stopping for buffering |
onchange |
script |
Triggers when an element changes |
onclick |
script |
Triggers on a mouse click |
oncontextmenu |
script |
Triggers when a context menu is triggered |
ondblclick |
script |
Triggers on a mouse double-click |
ondrag |
script |
Triggers when an element is dragged |
ondragend |
script |
Triggers at the end of a drag operation |
ondragenter |
script |
Triggers when an element has been dragged to a valid drop target |
ondragleave |
script |
Triggers when an element is being dragged over a valid drop target |
ondragover |
script |
Triggers at the start of a drag operation |
ondragstart |
script |
Triggers at the start of a drag operation |
ondrop |
script |
Triggers when dragged element is being dropped |
ondurationchange |
script |
Triggers when the length of the media is changed |
onemptied |
script |
Triggers when a media resource element suddenly becomes empty. |
onended |
script |
Triggers when media has reach the end |
onerror |
script |
Triggers when an error occur |
onfocus |
script |
Triggers when the window gets focus |
onformchange |
script |
Triggers when a form changes |
onforminput |
script |
Triggers when a form gets user input |
onhaschange |
script |
Triggers when the document has change |
oninput |
script |
Triggers when an element gets user input |
oninvalid |
script |
Triggers when an element is invalid |
onkeydown |
script |
Triggers when a key is pressed |
onkeypress |
script |
Triggers when a key is pressed and released |
onkeyup |
script |
Triggers when a key is released |
onload |
script |
Triggers when the document loads |
onloadeddata |
script |
Triggers when media data is loaded |
onloadedmetadata |
script |
Triggers when the duration and other media data of a media element is loaded |
onloadstart |
script |
Triggers when the browser starts to load the media data |
onmessage |
script |
Triggers when the message is triggered |
onmousedown |
script |
Triggers when a mouse button is pressed |
onmousemove |
script |
Triggers when the mouse pointer moves |
onmouseout |
script |
Triggers when the mouse pointer moves out of an element |
onmouseover |
script |
Triggers when the mouse pointer moves over an element |
onmouseup |
script |
Triggers when a mouse button is released |
onmousewheel |
script |
Triggers when the mouse wheel is being rotated |
onoffline |
script |
Triggers when the document goes offline |
onoine |
script |
Triggers when the document comes online |
ononline |
script |
Triggers when the document comes online |
onpagehide |
script |
Triggers when the window is hidden |
onpageshow |
script |
Triggers when the window becomes visible |
onpause |
script |
Triggers when media data is paused |
onplay |
script |
Triggers when media data is going to start playing |
onplaying |
script |
Triggers when media data has start playing |
onpopstate |
script |
Triggers when the window’s history changes |
onprogress |
script |
Triggers when the browser is fetching the media data |
onratechange |
script |
Triggers when the media data’s playing rate has changed |
onreadystatechange |
script |
Triggers when the ready-state changes |
onredo |
script |
Triggers when the document performs a redo |
onresize |
script |
Triggers when the window is resized |
onscroll |
script |
Triggers when an element’s scrollbar is being scrolled |
onseeked |
script |
Triggers when a media element’s seeking attribute is no longer true, and the seeking has ended |
onseeking |
script |
Triggers when a media element’s seeking attribute is true, and the seeking has begun |
onselect |
script |
Triggers when an element is selected |
onstalled |
script |
Triggers when there is an error in fetching media data |
onstorage |
script |
Triggers when a document loads |
onsubmit |
script |
Triggers when a form is submitted |
onsuspend |
script |
Triggers when the browser has been fetching media data, but stopped before the entire media file was fetched |
ontimeupdate |
script |
Triggers when media changes its playing position |
onundo |
script |
Triggers when a document performs an undo |
onunload |
script |
Triggers when the user leaves the document |
onvolumechange |
script |
Triggers when media changes the volume, also when volume is set to "mute" |
onwaiting |
script |
Triggers when media has stopped playing, but is expected to resume |
JavaScript and Cookies
What are Cookies ?
Web 浏览器和服务器使用 HTTP 协议进行通信,而 HTTP 是一个无状态协议。但是,对于商业网站而言,需要在不同页面之间维护会话信息。例如,用户完成多个页面的操作后结束注册。但是,如何在所有网页中维护用户会话信息。
Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. But how to maintain users' session information across all the web pages.
在许多情况下,使用 cookie 是记忆和跟踪偏好、购买、佣金和其他信息最有效的方法,而这些信息对于提升访问者体验或网站统计至关重要。
In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.
How It Works ?
您的服务器以 cookie 的形式向访问者的浏览器发送部分数据。浏览器可能会接收该 cookie。如果接受,它会以纯文本记录的形式存储在访问者的硬盘上。现在,当访问者访问您网站上的另一个页面时,浏览器会向服务器发送相同的 cookie 以供检索。检索后,您的服务器会知道/记住之前存储的内容。
Your server sends some data to the visitor’s browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor’s hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.
Cookie 是纯文本数据记录,包含 5 个可变长度字段:
Cookies are a plain text data record of 5 variable-length fields −
-
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
-
Domain − The domain name of your site.
-
Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
-
Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
-
Name=Value − Cookies are set and retrieved in the form of key-value pairs
Cookie 的最初设计是为了 CGI 编程。Cookie 中包含的数据会自动在 Web 浏览器和 Web 服务器之间传输,这样服务器上的 CGI 脚本就能读取和写入存储在客户端上的 Cookie 值。
Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client.
JavaScript 也可以使用 Document 对象的 cookie 属性来操作 Cookie。JavaScript 能读取、创建、修改和删除适用于当前网页的 Cookie。
JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page.
Storing Cookies
创建 Cookie 的最简单的方法是将一个字符串值分配给 document.cookie 对象,如下所示。
The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this.
document.cookie = "key1 = value1;key2 = value2;expires = date";
这里的 expires 属性是可选的。如果您使用有效日期或时间提供这个属性,则 Cookie 将在给定的日期或时间过期,此后无法再访问 Cookie 的值。
Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.
Note - Cookie 值不能包含分号、逗号或空格。由于此原因,您可能希望在将 JavaScript escape() 函数编码后存储在 Cookie 中之前使用该函数。如果您这么做,在读取 Cookie 值时,您还必须使用相应的 unescape() 函数。
Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value.
Example
尝试以下操作。它在输入 Cookie 中设置一个客户名称。
Try the following. It sets a customer name in an input 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>
Reading Cookies
读取 Cookie 和编写 Cookie 同样简单,因为 document.cookie 对象的值就是 Cookie。因此,每次您要访问 Cookie 时,都可以使用这个字符串。document.cookie 字符串将保留一个由分号分隔的名值对列表,其中 name 是 Cookie 的名称,value 是它的字符串值。
Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value.
您可以使用字符串的 split() 函数将字符串分解为键和值,如下所示 -
You can use strings' split() function to break a string into key and values as follows −
Example
尝试以下示例以获取所有 Cookie。
Try the following example to get all the cookies.
<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 - 这里 length 是 Array 类的某个方法,它返回数组的长度。我们在单独章节中讨论数组。在讨论之前,请尝试理解一下。
Note − Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that time, please try to digest it.
Note - 您的计算机中可能已经设置了其他一些 Cookie。以上代码将显示计算机中设置的所有 Cookie。
Note − There may be some other cookies already set on your machine. The above code will display all the cookies set on your machine.
Setting Cookies Expiry Date
您可以通过设置一个过期日期并在 Cookie 中保存过期日期来将 Cookie 的生存期延长到当前浏览器会话之后。这可以通过设置 ‘expires’ 属性为一个日期和时间来实现。
You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the ‘expires’ attribute to a date and time.
Example
尝试以下示例。它说明如何将 Cookie 的过期日期延长 1 个月。
Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.
<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>
Deleting a Cookie
有时,您会希望删除一个 Cookie,以便后续尝试读取 Cookie 时没有任何返回结果。要做到这一点,您只需要将过期日期设置为过去的时间。
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiry date to a time in the past.
Example
尝试以下示例。它说明如何通过将过期日期设置为当前日期之前的一个月来删除 Cookie。
Try the following example. It illustrates how to delete a cookie by setting its expiry date to one month behind the current date.
<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>
JavaScript - Page Redirection
What is Page Redirection ?
您可能遇到过如下情况,点击了一个 URL 以访问页面 X,但您在内部被导向了另一个页面 Y。这种情况是 page redirection 导致的。这个概念不同于 JavaScript Page Refresh 。
You might have encountered a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection. This concept is different from JavaScript Page Refresh.
您希望将用户从原始页面重定向的原因可能有多种。我们列出了其中一些原因 -
There could be various reasons why you would like to redirect a user from the original page. We are listing down a few of the reasons −
-
You did not like the name of your domain and you are moving to a new one. In such a scenario, you may want to direct all your visitors to the new site. Here you can maintain your old domain but put a single page with a page redirection such that all your old domain visitors can come to your new domain.
-
You have built-up various pages based on browser versions or their names or may be based on different countries, then instead of using your server-side page redirection, you can use client-side page redirection to land your users on the appropriate page.
-
The Search Engines may have already indexed your pages. But while moving to another domain, you would not like to lose your visitors coming through search engines. So you can use client-side page redirection. But keep in mind this should not be done to fool the search engine, it could lead your site to get banned.
How Page Re-direction Works ?
页面重定向的实现如下。
The implementations of Page-Redirection are as follows.
Example 1
使用客户端的 JavaScript 进行页面重定向非常简单。要将网站访问者重定向到一个新页面,你只需在头部分中添加一个如下所示的行。
It is quite simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows.
<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>
Example 2
在将网站访问者重定向到一个新页面之前,你可以向他们显示适当的信息。这需要一点时间来加载一个新页面。下面的示例展示了如何实现该方法。其中 setTimeout() 是一个内置 JavaScript 函数, 可用于在给定时间间隔后执行另一个函数。
You can show an appropriate message to your site visitors before redirecting them to a new page. This would need a bit time delay to load a new page. The following example shows how to implement the same. Here setTimeout() is a built-in JavaScript function which can be used to execute another function after a given time interval.
<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>
Example 3
下面的示例展示了如何根据浏览器将网站访问者重定向到一个不同的页面。
The following example shows how to redirect your site visitors onto a different page based on their browsers.
<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 支持三种重要的对话框类型。这些对话框可用于发出警告或确认任何输入,或获取用户的一种输入。这里我们将一一讨论每个对话框。
JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of input from the users. Here we will discuss each dialog box one by one.
Alert Dialog Box
警报对话框主要用于向用户发出警告信息。例如,如果一个输入字段需要输入文本,但用户未提供任何输入,那么作为验证的一部分,你可以使用一个警报框来发出警告信息。
An alert dialog box is mostly used to give a warning message to the users. For example, if one input field requires to enter some text but the user does not provide any input, then as a part of validation, you can use an alert box to give a warning message.
此外,警报框可用于更友好的信息。警报框仅提供一个按钮“确定”供用户选择并继续。
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button "OK" to select and proceed.
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>
Confirmation Dialog Box
确认对话框主要用于获取用户的同意选项。它显示一个带有两个按钮的对话框: OK 和 Cancel 。
A confirmation dialog box is mostly used to take user’s consent on any option. It displays a dialog box with two buttons: OK and Cancel.
如果用户单击确定按钮,则窗口方法 confirm() 将返回 true。如果用户单击取消按钮,则 confirm() 将返回 false。你可以如下使用确认对话框。
If the user clicks on the OK button, the window method confirm() will return true. If the user clicks on the Cancel button, then confirm() returns false. You can use a confirmation dialog box as follows.
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>
Prompt Dialog Box
当你想要弹出文本框以获取用户输入时,提示对话框非常有用。因此,它使你能够与用户进行交互。用户需要填写该字段,然后单击确定。
The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it enables you to interact with the user. The user needs to fill in the field and then click OK.
使用一个名为 prompt() 的方法显示此对话框,该方法采用两个参数:(i) 想在文本框中显示的标签和 (ii) 想在文本框中显示的默认字符串。
This dialog box is displayed using a method called prompt() which takes two parameters: (i) a label which you want to display in the text box and (ii) a default string to display in the text box.
此对话框有两个按钮: OK 和 Cancel 。如果用户单击确定按钮,则窗口方法 prompt() 将返回从文本框输入的值。如果用户单击取消按钮,则窗口方法 prompt() 将返回 null 。
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window method prompt() will return the entered value from the text box. If the user clicks the Cancel button, the window method prompt() returns null.
Example
以下示例展示如何使用提示对话框 −
The following example shows how to use a prompt dialog box −
<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>
JavaScript - Void Keyword
void 是 JavaScript 中的一个重要关键字,可作为一元运算符使用,它出现在其单个操作数之前,该操作数可以是任何类型。此运算符指定要计算而不返回值的表达式。
void is an important keyword in JavaScript which can be used as a unary operator that appears before its single operand, which may be of any type. This operator specifies an expression to be evaluated without returning a value.
Syntax
void 的语法可以是以下两种之一 −
The syntax of void can be either of the following two −
<head>
<script type = "text/javascript">
<!--
void func()
javascript:void func()
or:
void(func())
javascript:void(func())
//-->
</script>
</head>
Example 1
此运算符最常见的用途是在客户端 javascript:URL 中,它允许你计算表达式的副作用,而无需浏览器显示计算表达式 的值。
The most common use of this operator is in a client-side javascript: URL, where it allows you to evaluate an expression for its side-effects without the browser displaying the value of the evaluated expression.
这里对表达式 alert ('Warning!!!') 进行了计算,但不会将其加载回当前文档中 −
Here the expression alert ('Warning!!!') is evaluated but it is not loaded back into the current document −
<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>
Example 2
仔细查看下面的示例。下面的链接没有任何作用,因为 JavaScript 中的表达式“0”没有效果。在这里,“0”表达式被求值,但它不会被重新加载到当前文档中。
Take a look at the following example. The following link does nothing because the expression "0" has no effect in JavaScript. Here the expression "0" is evaluated, but it is not loaded back into the current document.
<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>
Example 3
void 的另一个使用是用它执行如下动作,来特意生成 undefined 值。
Another use of void is to purposely generate the undefined value as follows.
<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>
JavaScript - Page Printing
很多时候,希望在你的网页中放置一个按钮,以此通过实际打印机打印该网页的内容。JavaScript 帮助你使用 window 对象的 print 函数来实现这一功能。
Many times you would like to place a button on your webpage to print the content of that web page via an actual printer. JavaScript helps you to implement this functionality using the print function of window object.
JavaScript print 函数 window.print() 在执行时会打印当前网页。你可以直接使用 onclick 事件来调用此函数,如下面的示例所示。
The JavaScript print function window.print() prints the current web page when executed. You can call this function directly using the onclick event as shown in the following example.
Example
尝试以下示例。
Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
//-->
</script>
</head>
<body>
<form>
<input type = "button" value = "Print" onclick = "window.print()" />
</form>
</body>
<html>
Output
尽管它对获取打印输出有帮助,但它并不是一种推荐的方法。对于打印机来说,友好页面其实就是没有图像、图形或广告副本的页面。
Although it serves the purpose of getting a printout, it is not a recommended way. A printer friendly page is really just a page with text, no images, graphics, or advertising.
你可以通过以下方法让网页成为打印机友好型页面:
You can make a page printer friendly in the following ways −
-
Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example.
-
If you do not want to keep an extra copy of a page, then you can mark your printable text using proper comments like <!-- PRINT STARTS HERE -→….. <!-- PRINT ENDS HERE -→ and then you can use PERL or any other script in the background to purge printable text and display for final printing. We at Tutorialspoint use this method to provide print facility to our site visitors.
JavaScript - Objects Overview
JavaScript 是一种面向对象编程 (OOP) 语言。如果编程语言为开发人员提供了以下四种基本功能,则该编程语言可以被称为面向对象编程语言:
JavaScript is an Object Oriented Programming (OOP) language. A programming language can be called object-oriented if it provides four basic capabilities to developers −
-
Encapsulation − the capability to store related information, whether data or methods, together in an object.
-
Aggregation − the capability to store one object inside another object.
-
Inheritance − the capability of a class to rely upon another class (or number of classes) for some of its properties and methods.
-
Polymorphism − the capability to write one function or method that works in a variety of different ways.
对象由属性组成。如果属性包含一个函数,那么它会被视为对象的一种方法,否则该属性会被视为一种属性。
Objects are composed of attributes. If an attribute contains a function, it is considered to be a method of the object, otherwise the attribute is considered a property.
Object Properties
对象属性可以是三种基本数据类型中的任何一种,或任何抽象数据类型,例如另一个对象。对象属性通常是在对象的函数中内部使用的变量,但它也可以是贯穿整个页面使用的全局变量。
Object properties can be any of the three primitive data types, or any of the abstract data types, such as another object. Object properties are usually variables that are used internally in the object’s methods, but can also be globally visible variables that are used throughout the page.
向对象添加属性的语法为:
The syntax for adding a property to an object is −
objectName.objectProperty = propertyValue;
For example − 以下代码使用 document 对象的 "title" 属性获取文档标题。
For example − The following code gets the document title using the "title" property of the document object.
var str = document.title;
Object Methods
方法是让对象做某事或让某些事对对象执行的函数。函数与方法之间存在小差异 - 函数是一个独立的语句单元,而方法依附于对象,并且可以由 this 关键字引用。
Methods are the functions that let the object do something or let something be done to it. There is a small difference between a function and a method – at a function is a standalone unit of statements and a method is attached to an object and can be referenced by the this keyword.
这些方法对从显示对象内容到屏幕到对一组局部属性和参数执行复杂数学运算的所有内容都很有用。
Methods are useful for everything from displaying the contents of the object to the screen to performing complex mathematical operations on a group of local properties and parameters.
For example - 以下是一个简单的示例,展示如何使用文档对象的 write() 方法写入文档中任何内容。
For example − Following is a simple example to show how to use the write() method of document object to write any content on the document.
document.write("This is test");
User-Defined Objects
所有用户定义的对象和内置的对象都是称为 Object 的对象的子项。
All user-defined objects and built-in objects are descendants of an object called Object.
The new Operator
new 运算符用于创建对象的实例。要创建对象, new 运算符后跟构造方法。
The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method.
在以下示例中,构造方法为 Object()、Array() 和 Date()。这些构造函数是内置的 JavaScript 函数。
In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are built-in JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
The Object() Constructor
构造函数是一个用于创建和初始化对象的功能。JavaScript 提供了一个名为 Object() 的特殊构造函数来构建对象。 Object() 构造函数的返回值被分配给一个变量。
A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function called Object() to build the object. The return value of the Object() constructor is assigned to a variable.
该变量包含对新对象的引用。分配给对象的属性不是变量,并且没有使用 var 关键字定义。
The variable contains a reference to the new object. The properties assigned to the object are not variables and are not defined with the var keyword.
Example 1
尝试以下示例;它演示如何创建对象。
Try the following example; it demonstrates how to create an Object.
<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>
Example 2
此示例演示如何使用用户定义函数创建对象。在这里, this 关键字用于引用已传递给函数的对象。
This example demonstrates how to create an object with a User-Defined Function. Here this keyword is used to refer to the object that has been passed to a function.
<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>
Defining Methods for an Object
前面的示例演示了构造函数如何创建对象并分配属性。但是我们需要通过向其分配方法来完成对对象的定义。
The previous examples demonstrate how the constructor creates the object and assigns properties. But we need to complete the definition of an object by assigning methods to it.
Example
尝试以下示例;它显示如何将一个函数与一个对象一起添加。
Try the following example; it shows how to add a function along with an object.
<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>
The 'with' Keyword
‘with’ 关键字用作引用对象属性或方法的一种速记。
The ‘with’ keyword is used as a kind of shorthand for referencing an object’s properties or methods.
作为 with 的参数指定的对象成为随后块的默认对象。可以在没有使用对象名称的情况下使用对象的属性和方法。
The object specified as an argument to with becomes the default object for the duration of the block that follows. The properties and methods for the object can be used without naming the object.
Syntax
with object 的语法如下 -
The syntax for with object is as follows −
with (object) {
properties used without the object name and dot
}
Example
尝试以下示例。
Try the following 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>
JavaScript Native Objects
JavaScript 有几个内置的或本地的对象。这些对象可以访问程序的任何地方,并且在运行于任何操作系统中的任何浏览器中都将以相同的方式工作。
JavaScript has several built-in or native objects. These objects are accessible anywhere in your program and will work the same way in any browser running in any operating system.
以下是所有重要的 JavaScript 本地对象列表 -
Here is the list of all important JavaScript Native Objects −
JavaScript - The Number Object
Number 对象表示数值日期,无论是整数还是浮点数。通常,你不必担心 Number 对象,因为浏览器会自动将数字常量转换为数字类的实例。
The Number object represents numerical date, either integers or floating-point numbers. In general, you do not need to worry about Number objects because the browser automatically converts number literals to instances of the number class.
Syntax
创建 number 对象的语法如下 -
The syntax for creating a number object is as follows −
var val = new Number(number);
在 number 的位置,如果你提供任何非数字参数,则参数不能转换为数字,则它返回 NaN (不是数字)。
In the place of number, if you provide any non-number argument, then the argument cannot be converted into a number, it returns NaN (Not-a-Number).
Number Properties
以下列出每个属性和它们的说明。
Here is a list of each property and their description.
Sr.No. |
Property & Description |
1 |
MAX_VALUEThe largest possible value a number in JavaScript can have 1.7976931348623157E+308 |
2 |
MIN_VALUEThe smallest possible value a number in JavaScript can have 5E-324 |
3 |
NaNEqual to a value that is not a number. |
4 |
NEGATIVE_INFINITYA value that is less than MIN_VALUE. |
5 |
POSITIVE_INFINITYA value that is greater than MAX_VALUE |
6 |
prototypeA static property of the Number object. Use the prototype property to assign new properties and methods to the Number object in the current document |
7 |
constructorReturns the function that created this object’s instance. By default this is the Number object. |
在以下各节中,我们将举几个示例来说明 Number 的属性。
In the following sections, we will take a few examples to demonstrate the properties of Number.
Number Methods
Number 对象仅包含作为每个对象定义的一部分的默认方法。
The Number object contains only the default methods that are a part of every object’s definition.
Sr.No. |
Method & Description |
1 |
toExponential()Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation. |
2 |
toFixed()Formats a number with a specific number of digits to the right of the decimal. |
3 |
toLocaleString()Returns a string value version of the current number in a format that may vary according to a browser’s local settings. |
4 |
toPrecision()Defines how many total digits (including digits to the left and right of the decimal) to display of a number. |
5 |
toString()Returns the string representation of the number’s value. |
6 |
valueOf()Returns the number’s value. |
在以下各节中,我们将举几个示例来说明 Number 的方法。
In the following sections, we will have a few examples to explain the methods of Number.
JavaScript - The Boolean Object
Boolean 对象表示两个值,“true”或“false”。如果省略了 value 参数或该参数为 0、-0、null、false、 NaN, undefined 或空字符串 (""),则对象初始值将为 false。
The Boolean object represents two values, either "true" or "false". If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.
Syntax
使用以下语法创建 boolean 对象。
Use the following syntax to create a boolean object.
var val = new Boolean(value);
Boolean Properties
以下列出 Boolean 对象的属性:
Here is a list of the properties of Boolean object −
Sr.No. |
Property & Description |
1 |
constructorReturns a reference to the Boolean function that created the object. |
2 |
prototypeThe prototype property allows you to add properties and methods to an object. |
在以下部分,我们将通过几个示例来说明布尔对象的属性。
In the following sections, we will have a few examples to illustrate the properties of Boolean object.
Boolean Methods
以下是布尔对象的方法及其说明的列表。
Here is a list of the methods of Boolean object and their description.
Sr.No. |
Method & Description |
1 |
toSource()Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object. |
2 |
toString()Returns a string of either "true" or "false" depending upon the value of the object. |
3 |
valueOf()Returns the primitive value of the Boolean object. |
在以下部分,我们将通过几个示例演示布尔方法的使用。
In the following sections, we will have a few examples to demonstrate the usage of the Boolean methods.
JavaScript - The Strings Object
String 对象允许您使用一系列字符;它用多个辅助方法包装 Javascript 字符串基元数据类型。
The String object lets you work with a series of characters; it wraps Javascript’s string primitive data type with a number of helper methods.
由于 JavaScript 会在字符串基元和 String 对象之间自动转换,因此您可以在字符串基元上调用 String 对象的任何辅助方法。
As JavaScript automatically converts between string primitives and String objects, you can call any of the helper methods of the String object on a string primitive.
Syntax
使用以下语法创建 String 对象 −
Use the following syntax to create a String object −
var val = new String(string);
String 参数是已正确编码的一系列字符。
The String parameter is a series of characters that has been properly encoded.
String Properties
以下是 String 对象的属性及其说明的列表。
Here is a list of the properties of String object and their description.
Sr.No. |
Property & Description |
1 |
constructorReturns a reference to the String function that created the object. |
2 |
lengthReturns the length of the string. |
3 |
prototypeThe prototype property allows you to add properties and methods to an object. |
在以下部分,我们将通过几个示例演示 String 属性的使用。
In the following sections, we will have a few examples to demonstrate the usage of String properties.
String Methods
以下是 String 对象中可用的方法及其说明的列表。
Here is a list of the methods available in String object along with their description.
Sr.No. |
Method & Description |
1 |
charAt()Returns the character at the specified index. |
2 |
charCodeAt()Returns a number indicating the Unicode value of the character at the given index. |
3 |
concat()Combines the text of two strings and returns a new string. |
4 |
indexOf()Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. |
5 |
lastIndexOf()Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. |
6 |
localeCompare()Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. |
7 |
match()Used to match a regular expression against a string. |
8 |
replace()Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring. |
9 |
search()Executes the search for a match between a regular expression and a specified string. |
10 |
slice()Extracts a section of a string and returns a new string. |
11 |
split()Splits a String object into an array of strings by separating the string into substrings. |
12 |
substr()Returns the characters in a string beginning at the specified location through the specified number of characters. |
13 |
substring()Returns the characters in a string between two indexes into the string. |
14 |
toLocaleLowerCase()The characters within a string are converted to lower case while respecting the current locale. |
15 |
toLocaleUpperCase()The characters within a string are converted to upper case while respecting the current locale. |
16 |
toLowerCase()Returns the calling string value converted to lower case. |
17 |
toString()Returns a string representing the specified object. |
18 |
toUpperCase()Returns the calling string value converted to uppercase. |
19 |
valueOf()Returns the primitive value of the specified object. |
String HTML Wrappers
以下是返回用适当的 HTML 标签包装的字符串副本的方法列表。
Here is a list of the methods that return a copy of the string wrapped inside an appropriate HTML tag.
Sr.No. |
Method & Description |
1 |
anchor()Creates an HTML anchor that is used as a hypertext target. |
2 |
big()Creates a string to be displayed in a big font as if it were in a <big> tag. |
3 |
blink()Creates a string to blink as if it were in a <blink> tag. |
4 |
bold()Creates a string to be displayed as bold as if it were in a <b> tag. |
5 |
fixed()Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag |
6 |
fontcolor()Causes a string to be displayed in the specified color as if it were in a <font color="color"> tag. |
7 |
fontsize()Causes a string to be displayed in the specified font size as if it were in a <font size="size"> tag. |
8 |
italics()Causes a string to be italic, as if it were in an <i> tag. |
9 |
link()Creates an HTML hypertext link that requests another URL. |
10 |
small()Causes a string to be displayed in a small font, as if it were in a <small> tag. |
11 |
strike()Causes a string to be displayed as struck-out text, as if it were in a <strike> tag. |
12 |
sub()Causes a string to be displayed as a subscript, as if it were in a <sub> tag |
13 |
sup()Causes a string to be displayed as a superscript, as if it were in a <sup> tag |
在以下部分中,我们将演示几个示例来展示 String 方法的用法。
In the following sections, we will have a few examples to demonstrate the usage of String methods.
JavaScript - The Arrays Object
Array 对象允许您在单个变量中存储多个值。它存储一个相同类型的元素组成的固定大小顺序集合。数组用于存储数据集合,但通常将其视为同一类型的变量集合更有用。
The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Syntax
使用以下语法创建 Array 对象 −
Use the following syntax to create an Array object −
var fruits = new Array( "apple", "orange", "mango" );
Array 参数是字符串或整数的列表。当您使用 Array 构造函数指定单个数字参数时,将指定数组的初始长度。一个数组允许的最大长度为 4,294,967,295。
The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The maximum length allowed for an array is 4,294,967,295.
您可以通过简单地分配值来创建数组,如下所示 −
You can create array by simply assigning values as follows −
var fruits = [ "apple", "orange", "mango" ];
你将使用序数来访问并设置数组中的值,如下所示。
You will use ordinal numbers to access and to set values inside an array as follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element
Array Properties
以下是 Array 对象的属性列表及其描述。
Here is a list of the properties of the Array object along with their description.
Sr.No. |
Property & Description |
1 |
constructorReturns a reference to the array function that created the object. |
2 |
index The property represents the zero-based index of the match in the string |
3 |
input This property is only present in arrays created by regular expression matches. |
4 |
length Reflects the number of elements in an array. |
5 |
prototypeThe prototype property allows you to add properties and methods to an object. |
在以下部分中,我们将举几个示例来说明 Array 属性的用法。
In the following sections, we will have a few examples to illustrate the usage of Array properties.
Array Methods
下面列出了 Array 对象的方法及其描述。
Here is a list of the methods of the Array object along with their description.
Sr.No. |
Method & Description |
1 |
concat()Returns a new array comprised of this array joined with other array(s) and/or value(s). |
2 |
every()Returns true if every element in this array satisfies the provided testing function. |
3 |
filter()Creates a new array with all of the elements of this array for which the provided filtering function returns true. |
4 |
forEach()Calls a function for each element in the array. |
5 |
indexOf()Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. |
6 |
join()Joins all elements of an array into a string. |
7 |
lastIndexOf()Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. |
8 |
map()Creates a new array with the results of calling a provided function on every element in this array. |
9 |
pop()Removes the last element from an array and returns that element. |
10 |
push()Adds one or more elements to the end of an array and returns the new length of the array. |
11 |
reduce()Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value. |
12 |
reduceRight()Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value. |
13 |
reverse()Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first. |
14 |
shift()Removes the first element from an array and returns that element. |
15 |
slice()Extracts a section of an array and returns a new array. |
16 |
some()Returns true if at least one element in this array satisfies the provided testing function. |
17 |
toSource()Represents the source code of an object |
18 |
sort()Sorts the elements of an array |
19 |
splice()Adds and/or removes elements from an array. |
20 |
toString()Returns a string representing the array and its elements. |
21 |
unshift()Adds one or more elements to the front of an array and returns the new length of the array. |
在下几节中, 我们将通过示例说明数组方法的使用。
In the following sections, we will have a few examples to demonstrate the usage of Array methods.
JavaScript - The Date Object
Date 对象是 JavaScript 语言中内置的数据类型。可使用 new Date( ) 创建 Date 对象, 如下所示。
The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) as shown below.
创建 Date 对象后, 多个方法允许你对其进行操作。大部分方法仅允许你获取和设置对象的年、月、日、小时、分钟、秒和毫秒字段, 使用本地时间或 UTC (通用或 GMT) 时间。
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.
ECMAScript 标准要求 Date 对象能表示任意日期和时间, 至毫秒精度, 于 1/1/1970 前后 1 亿天内。这是正负 273,785 年的范围, 因此 JavaScript 可以表示到 275755 年的日期和时间。
The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can represent date and time till the year 275755.
Syntax
你可以使用下列任意语法来使用 Date() 构造函数创建 Date 对象。
You can use any of the following syntaxes to create a Date object using Date() constructor.
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Note − 括号中的参数始终为可选。
Note − Parameters in the brackets are always optional.
以下是参数说明 −
Here is a description of the parameters −
-
No Argument − With no arguments, the Date() constructor creates a Date object set to the current date and time.
-
milliseconds − When one numeric argument is passed, it is taken as the internal numeric representation of the date in milliseconds, as returned by the getTime() method. For example, passing the argument 5000 creates a date that represents five seconds past midnight on 1/1/70.
-
datestring − When one string argument is passed, it is a string representation of a date, in the format accepted by the Date.parse() method.
-
7 agruments − To use the last form of the constructor shown above. Here is a description of each argument −
Date Properties
以下是 Date 对象的属性列表及其描述。
Here is a list of the properties of the Date object along with their description.
Sr.No. |
Property & Description |
1 |
constructorSpecifies the function that creates an object’s prototype. |
2 |
prototypeThe prototype property allows you to add properties and methods to an object |
在以下部分中,我们将提供一些示例以演示不同日期属性的用法。
In the following sections, we will have a few examples to demonstrate the usage of different Date properties.
Date Methods
下面列出了 Date 中使用的方法及其说明。
Here is a list of the methods used with Date and their description.
Sr.No. |
Method & Description |
1 |
Date()Returns today’s date and time |
2 |
getDate()Returns the day of the month for the specified date according to local time. |
3 |
getDay()Returns the day of the week for the specified date according to local time. |
4 |
getFullYear()Returns the year of the specified date according to local time. |
5 |
getHours()Returns the hour in the specified date according to local time. |
6 |
getMilliseconds()Returns the milliseconds in the specified date according to local time. |
7 |
getMinutes()Returns the minutes in the specified date according to local time. |
8 |
getMonth()Returns the month in the specified date according to local time. |
9 |
getSeconds()Returns the seconds in the specified date according to local time. |
10 |
getTime()Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. |
11 |
getTimezoneOffset()Returns the time-zone offset in minutes for the current locale. |
12 |
getUTCDate()Returns the day (date) of the month in the specified date according to universal time. |
13 |
getUTCDay()Returns the day of the week in the specified date according to universal time. |
14 |
getUTCFullYear()Returns the year in the specified date according to universal time. |
15 |
getUTCHours()Returns the hours in the specified date according to universal time. |
16 |
getUTCMilliseconds()Returns the milliseconds in the specified date according to universal time. |
17 |
getUTCMinutes()Returns the minutes in the specified date according to universal time. |
18 |
getUTCMonth()Returns the month in the specified date according to universal time. |
19 |
getUTCSeconds()Returns the seconds in the specified date according to universal time. |
20 |
getYear()Deprecated - Returns the year in the specified date according to local time. Use getFullYear instead. |
21 |
setDate()Sets the day of the month for a specified date according to local time. |
22 |
setFullYear()Sets the full year for a specified date according to local time. |
23 |
setHours()Sets the hours for a specified date according to local time. |
24 |
setMilliseconds()Sets the milliseconds for a specified date according to local time. |
25 |
setMinutes()Sets the minutes for a specified date according to local time. |
26 |
setMonth()Sets the month for a specified date according to local time. |
27 |
setSeconds()Sets the seconds for a specified date according to local time. |
28 |
setTime()Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. |
29 |
setUTCDate()Sets the day of the month for a specified date according to universal time. |
30 |
setUTCFullYear()Sets the full year for a specified date according to universal time. |
31 |
setUTCHours()Sets the hour for a specified date according to universal time. |
32 |
setUTCMilliseconds()Sets the milliseconds for a specified date according to universal time. |
33 |
setUTCMinutes()Sets the minutes for a specified date according to universal time. |
34 |
setUTCMonth()Sets the month for a specified date according to universal time. |
35 |
setUTCSeconds()Sets the seconds for a specified date according to universal time. |
36 |
setYear()*Deprecated - * Sets the year for a specified date according to local time. Use setFullYear instead. |
37 |
toDateString()Returns the "date" portion of the Date as a human-readable string. |
38 |
toGMTString()*Deprecated - * Converts a date to a string, using the Internet GMT conventions. Use toUTCString instead. |
39 |
toLocaleDateString()Returns the "date" portion of the Date as a string, using the current locale’s conventions. |
40 |
toLocaleFormat()Converts a date to a string, using a format string. |
41 |
toLocaleString()Converts a date to a string, using the current locale’s conventions. |
42 |
toLocaleTimeString()Returns the "time" portion of the Date as a string, using the current locale’s conventions. |
43 |
toSource()Returns a string representing the source for an equivalent Date object; you can use this value to create a new object. |
44 |
toString()Returns a string representing the specified Date object. |
45 |
toTimeString()Returns the "time" portion of the Date as a human-readable string. |
46 |
toUTCString()Converts a date to a string, using the universal time convention. |
47 |
valueOf()Returns the primitive value of a Date object. |
使用世界时约定将日期转换为字符串。
Converts a date to a string, using the universal time convention.
Date Static Methods
除了先前列出的许多实例方法外,Date 对象还定义了两个静态方法。这些方法通过 Date() 构造函数本身调用。
In addition to the many instance methods listed previously, the Date object also defines two static methods. These methods are invoked through the Date() constructor itself.
Sr.No. |
Method & Description |
1 |
Date.parse( )Parses a string representation of a date and time and returns the internal millisecond representation of that date. |
2 |
Date.UTC( )Returns the millisecond representation of the specified UTC date and time. |
在以下部分中,我们将通过一些示例来演示 Date 静态方法的使用。
In the following sections, we will have a few examples to demonstrate the usages of Date Static methods.
JavaScript - The Math Object
math 对象提供数学常数和函数的属性和方法。与其他全局对象不同, Math 不是构造函数。 Math 的所有属性和方法都是静态的,可以通过将 Math 用作对象而不创建它来调用。
The math object provides you properties and methods for mathematical constants and functions. Unlike other global objects, Math is not a constructor. All the properties and methods of Math are static and can be called by using Math as an object without creating it.
因此,你可以引用 Math.PI 中的 pi 常量,并且你可以将 Math.sin(x) 调用为正弦函数,其中 x 是该方法的参数。
Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method’s argument.
Syntax
调用 Math 的属性和方法的语法如下所述:
The syntax to call the properties and methods of Math are as follows
var pi_val = Math.PI;
var sine_val = Math.sin(30);
Math Properties
以下是 Math 的所有属性及其描述的列表。
Here is a list of all the properties of Math and their description.
Sr.No. |
Property & Description |
1 |
link:../javascript/math_e.html[E \]Euler’s constant and the base of natural logarithms, approximately 2.718. |
2 |
LN2Natural logarithm of 2, approximately 0.693. |
3 |
LN10Natural logarithm of 10, approximately 2.302. |
4 |
LOG2EBase 2 logarithm of E, approximately 1.442. |
5 |
LOG10EBase 10 logarithm of E, approximately 0.434. |
6 |
PIRatio of the circumference of a circle to its diameter, approximately 3.14159. |
7 |
SQRT1_2Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707. |
8 |
SQRT2Square root of 2, approximately 1.414. |
在以下部分中,我们将提供一些示例来说明如何使用 Math 属性。
In the following sections, we will have a few examples to demonstrate the usage of Math properties.
Math Methods
以下是与 Math 对象关联的方法及其描述的列表:
Here is a list of the methods associated with Math object and their description
Sr.No. |
Method & Description |
1 |
abs()Returns the absolute value of a number. |
2 |
acos()Returns the arccosine (in radians) of a number. |
3 |
asin()Returns the arcsine (in radians) of a number. |
4 |
atan()Returns the arctangent (in radians) of a number. |
5 |
atan2()Returns the arctangent of the quotient of its arguments. |
6 |
ceil()Returns the smallest integer greater than or equal to a number. |
7 |
cos()Returns the cosine of a number. |
8 |
exp()Returns EN, where N is the argument, and E is Euler’s constant, the base of the natural logarithm. |
9 |
floor()Returns the largest integer less than or equal to a number. |
10 |
log()Returns the natural logarithm (base E) of a number. |
11 |
max()Returns the largest of zero or more numbers. |
12 |
min()Returns the smallest of zero or more numbers. |
13 |
pow()Returns base to the exponent power, that is, base exponent. |
14 |
random()Returns a pseudo-random number between 0 and 1. |
15 |
round()Returns the value of a number rounded to the nearest integer. |
16 |
sin()Returns the sine of a number. |
17 |
sqrt()Returns the square root of a number. |
18 |
tan()Returns the tangent of a number. |
19 |
toSource()Returns the string "Math". |
在以下部分中,我们将通过一些示例来说明与 Math 关联的方法的用法。
In the following sections, we will have a few examples to demonstrate the usage of the methods associated with Math.
Regular Expressions and RegExp Object
正则表达式是一个对象,描述一个字符模式。
A regular expression is an object that describes a pattern of characters.
JavaScript RegExp 类表示正则表达式,并且 String 和 RegExp 都定义了使用正则表达式来对文本执行强大的模式匹配和搜索替换功能的方法。
The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text.
Syntax
正则表达式可以用 RegExp () 构造函数定义,如下所示:
A regular expression could be defined with the RegExp () constructor, as follows −
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;
以下是参数说明 −
Here is the description of the parameters −
-
pattern − A string that specifies the pattern of the regular expression or another regular expression.
-
attributes − An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multi-line matches, respectively.
Brackets
括号 ([]) 在正则表达式中使用时具有特殊的含义。它们用于查找字符范围。
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters.
Sr.No. |
Expression & Description |
1 |
[…] Any one character between the brackets. |
2 |
[^…] Any one character not between the brackets. |
3 |
[0-9] It matches any decimal digit from 0 through 9. |
4 |
[a-z] It matches any character from lowercase a *through lowercase *z. |
5 |
[A-Z] It matches any character from uppercase A through uppercase Z. |
6 |
[a-Z] It matches any character from lowercase a through uppercase Z. |
上面显示的范围是通用的;你还可以使用范围 [0-3] 匹配 0 到 3 之间的任何十进制数字,或者使用范围 [b-v] 匹配小写 b 到 v 之间的任何小写字符。
The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.
Quantifiers
括号字符序列和单个字符的频率或位置可以通过特殊字符表示。每个特殊字符都有特定的含义。+, *, ?, 和 $ 标志都跟随一个字符序列。
The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a character sequence.
Sr.No. |
Expression & Description |
1 |
p+ It matches any string containing one or more p’s. |
2 |
p* It matches any string containing zero or more p’s. |
3 |
p? It matches any string containing at most one p. |
4 |
p{N} It matches any string containing a sequence of N p’s |
5 |
p{2,3} It matches any string containing a sequence of two or three p’s. |
6 |
p{2, } It matches any string containing a sequence of at least two p’s. |
7 |
p$ It matches any string with p at the end of it. |
8 |
^p It matches any string with p at the beginning of it. |
Examples
以下示例详细解释了如何匹配字符。
Following examples explain more about matching characters.
Sr.No. |
Expression & Description |
1 |
[^a-zA-Z] It matches any string not containing any of the characters ranging from a through z and A through Z. |
2 |
p.p It matches any string containing p, followed by any character, in turn followed by another p. |
3 |
^.{2}$ It matches any string containing exactly two characters. |
4 |
<b>(.)</b>* It matches any string enclosed within <b> and </b>. |
5 |
p(hp)* It matches any string containing a p followed by zero or more instances of the sequence 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 The Latin character specified by the hexadecimal number nn; for example, \x0A is the same as \n |
9 |
\uxxxx The Unicode character specified by the hexadecimal number xxxx; for example, \u0009 is the same as \t |
10 |
\cX The control character ^X; for example, \cJ is equivalent to the newline character \n |
Metacharacters
元字符只是一个字母字符,后面跟着一个反斜杠,用于赋予该组合特殊含义。
A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning.
例如,可以使用“\d”元字符搜索一大笔钱: /([\d]+)000/ ,此处 \d 将搜索包含所有数字字符的字符串。
For instance, you can search for a large sum of money using the '\d' metacharacter: /([\d]+)000/, Here \d will search for any string of numerical character.
下表列出了可在 PERL 样式正则表达式中使用的元字符。
The following table lists a set of metacharacters which can be used in PERL Style Regular Expressions.
Sr.No. |
Character & Description |
1 |
. a single character |
2 |
\s a whitespace character (space, tab, newline) |
3 |
\S non-whitespace character |
4 |
\d a digit (0-9) |
5 |
\D a non-digit |
6 |
\w a word character (a-z, A-Z, 0-9, _) |
7 |
\W a non-word character |
8 |
[\b] a literal backspace (special case). |
9 |
[aeiou] matches a single character in the given set |
10 |
[^aeiou] matches a single character outside the given set |
11 |
*(foo |
bar |
baz)* matches any of the alternatives specified |
Modifiers
几种修饰符可以简化使用 regexps, 的方式,例如大小写敏感、多行搜索等。
Several modifiers are available that can simplify the way you work with regexps, like case sensitivity, searching in multiple lines, etc.
Sr.No. |
Modifier & Description |
1 |
i Perform case-insensitive matching. |
2 |
m Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary |
3 |
g Performs a global matchthat is, find all matches rather than stopping after the first match. |
RegExp Properties
以下是与 RegExp 相关的属性及其描述的列表。
Here is a list of the properties associated with RegExp and their description.
Sr.No. |
Property & Description |
1 |
constructorSpecifies the function that creates an object’s prototype. |
2 |
globalSpecifies if the "g" modifier is set. |
3 |
ignoreCaseSpecifies if the "i" modifier is set. |
4 |
lastIndexThe index at which to start the next match. |
5 |
multilineSpecifies if the "m" modifier is set. |
6 |
sourceThe text of the pattern. |
在以下部分中,我们将提供一些示例来说明 RegExp 属性的用法。
In the following sections, we will have a few examples to demonstrate the usage of RegExp properties.
RegExp Methods
以下是与 RegExp 相关的函数及其描述的列表。
Here is a list of the methods associated with RegExp along with their description.
Sr.No. |
Method & Description |
1 |
exec()Executes a search for a match in its string parameter. |
2 |
test()Tests for a match in its string parameter. |
3 |
toSource()Returns an object literal representing the specified object; you can use this value to create a new object. |
4 |
toString()Returns a string representing the specified object. |
在以下几个部分中,我们将列出一些示例来说明正则表达式方法的使用。
In the following sections, we will have a few examples to demonstrate the usage of RegExp methods.
JavaScript - Document Object Model or DOM
每个网页都驻留在浏览器窗口内,该浏览器窗口可视为一个对象。
Every web page resides inside a browser window which can be considered as an object.
Document 对象表示显示在该窗口中的 HTML 文档。Document 对象具有各种属性,这些属性引用其他对象,用于允许访问和修改文档内容。
A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content.
访问和修改文档内容的方式称为 Document Object Model 或 DOM 。对象按层次结构组织。此层次结构适用于 Web 文档中对象的组织。
The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document.
-
Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.
-
Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page.
-
Form object − Everything enclosed in the <form>…</form> tags sets the form object.
-
Form control elements − The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes.
以下是几个重要对象的简单层次结构−
Here is a simple hierarchy of a few important objects −
存在多个 DOM。以下几个部分详细说明了每个 DOM,并描述了如何使用这些 DOM 来访问和修改文档内容。
There are several DOMs in existence. The following sections explain each of these DOMs in detail and describe how you can use them to access and modify document content.
-
The Legacy DOM − This is the model which was introduced in early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images.
-
The W3C DOM − This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the modern browsers.
-
The IE4 DOM − This document object model was introduced in Version 4 of Microsoft’s Internet Explorer browser. IE 5 and later versions include support for most basic W3C DOM features.
DOM compatibility
如果要编写一个脚本来灵活地根据其可用性使用 W3C DOM 或 IE 4 DOM,那么可以使用功能测试方法,该方法首先检查某个方法或属性是否存在,以确定浏览器是否具有你所希望的功能。例如:
If you want to write a script with the flexibility to use either W3C DOM or IE 4 DOM depending on their availability, then you can use a capability-testing approach that first checks for the existence of a method or property to determine whether the browser has the capability you desire. For example −
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) 逻辑错误。
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors.
Syntax Errors
语法错误,也称为 parsing errors, 发生在传统编程语言的编译时和 JavaScript 的解释时。
Syntax errors, also called parsing errors, occur at compile time in traditional programming languages and at interpret time in JavaScript.
例如,以下行会引发语法错误,因为它缺少一个结束括号。
For example, the following line causes a syntax error because it is missing a closing parenthesis.
<script type = "text/javascript">
<!--
window.print(;
//-->
</script>
当 JavaScript 中发生一个语法错误时,仅包含与该语法错误位于同一线程中的代码会受到影响,而其他线程中的其余代码会按假设它们不依赖于包含该错误的代码的方式执行。
When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax error is affected and the rest of the code in other threads gets executed assuming nothing in them depends on the code containing the error.
Runtime Errors
运行时错误,也称作 exceptions, 发生在执行期间(在编译/解释之后)。
Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).
例如,以下行会引发运行时错误,这是因为此处的语法正确,但在运行时它试图调用一个不存在的方法。
For example, the following line causes a runtime error because here the syntax is correct, but at runtime, it is trying to call a method that does not exist.
<script type = "text/javascript">
<!--
window.printme();
//-->
</script>
异常也会影响它们发生的线程,允许其他 JavaScript 线程继续正常执行。
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution.
Logical Errors
逻辑错误可能是最难追踪的错误类型。这些错误并非由语法或运行时错误导致的。它们发生在你的脚本的驱动逻辑中出现错误时,且你未得到预期的结果。
Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected.
你无法捕获这些错误,因为你想要在你的程序中置入哪种类型的逻辑取决于你的业务需求。
You cannot catch those errors, because it depends on your business requirement what type of logic you want to put in your program.
The try…catch…finally Statement
最新版本的 JavaScript 添加了异常处理能力。JavaScript 实现 try…catch…finally 结构和 throw 运算符来处理异常。
The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try…catch…finally construct as well as the throw operator to handle exceptions.
你可以 catch 由程序员产生的和 runtime 异常,但你不能 catch JavaScript 语法错误。
You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.
以下为 try…catch…finally 块语法 −
Here is the try…catch…finally block syntax −
<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 之后无条件执行。
The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch.
Examples
以下是一个我们试图调用一个不存在的函数的示例,该函数会引发异常。让我们看看在没有 try…catch 的情况下它的表现 −
Here is an example where we are trying to call a non-existing function which in turn is raising an exception. Let us see how it behaves without 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 捕获此异常并显示一条用户友好的消息。如果想对用户隐藏此错误,你也可以禁止显示此消息。
Now let us try to catch this exception using try…catch and display a user-friendly message. You can also suppress this message, if you want to hide this error from a user.
<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 之后。以下是一个示例。
You can use finally block which will always execute unconditionally after the try/catch. Here is an example.
<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>
The throw Statement
你可以使用 throw 语句引发你内置的异常或自定义的异常。之后可以捕获这些异常,你可以采取适当的行动。
You can use throw statement to raise your built-in exceptions or your customized exceptions. Later these exceptions can be captured and you can take an appropriate action.
Example
以下示例演示了如何使用 throw 语句。
The following example demonstrates how to use a throw statement.
<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 块在另一个函数中捕获该异常。
You can raise an exception in one function using a string, integer, Boolean, or an object and then you can capture that exception either in the same function as we did above, or in another function using a try…catch block.
The onerror() Method
onerror 事件处理程序是第一项允许在 JavaScript 中进行错误处理的功能。无论在页面上发生什么异常, error 事件都会在 window 对象上触发。
The onerror event handler was the first feature to facilitate error handling in JavaScript. The error event is fired on the window object whenever an exception occurs on the page.
<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 事件处理程序提供三项信息来识别错误的确切性质 −
The onerror event handler provides three pieces of information to identify the exact nature of the error −
-
Error message − The same message that the browser would display for the given error
-
URL − The file in which the error occurred
-
Line number− The line number in the given URL that caused the error
以下示例展示了如何提取此信息。
Here is the example to show how to extract this information.
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
你可以以你认为更合适的方式显示提取出的信息。
You can display extracted information in whatever way you think it is better.
你可以使用以下所示的` onerror `方法,在加载图片时出现任何问题的时候,显示错误信息。
You can use an onerror method, as shown below, to display an error message in case there is any problem in loading an image.
<img src="myimage.gif" onerror="alert('An error occurred loading the image.')" />
你可以使用` onerror `结合许多HTML标签,在出现错误的时候显示适当的消息。
You can use onerror with many HTML tags to display appropriate messages in case of errors.
JavaScript - Form Validation
表单验证通常在客户端输入所有必要数据并按下了提交按钮后在服务器上发生。如果客户端输入的数据不正确或丢失,服务器将不得不将所有数据发送回客户端,并要求使用正确的信息重新提交该表单。这确实是一个冗长的过程,过去给服务器带来了很大的负担。
Form validation normally used to occur at the server, after the client had entered all the necessary data and then pressed the Submit button. If the data entered by a client was incorrect or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process which used to put a lot of burden on the server.
Javascript 提供了一种方法,可以在将表单数据发送到 Web 服务器之前在客户端计算机上验证其数据。表单验证通常执行两个功能。
JavaScript provides a way to validate form’s data on the client’s computer before sending it to the web server. Form validation generally performs two functions.
-
Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
-
Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.
Example
我们将通过一个例子来了解验证的过程。以下是一个 html 格式的简单表单。
We will take an example to understand the process of validation. Here is a simple form in html format.
<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>
Basic Form Validation
首先让我们看看如何执行基本表单验证。在上述表单中,我们调用 validate() 以在 onsubmit 事件发生时验证数据。以下代码显示了该 validate() 函数的实现。
First let us see how to do a basic form validation. In the above form, we are calling validate() to validate data when onsubmit event is occurring. The following code shows the implementation of this validate() function.
<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 服务器之前验证我们的已输入表单数据。
Now we will see how we can validate our entered form data before submitting it to the web server.
以下示例显示了如何验证输入的电子邮件地址。电子邮件地址必须至少包含一个“@”符号和一个点(.)。此外,“@”不能是电子邮件地址的第一个字符,而最后一个点必须至少是“@”符号之后的一个字符。
The following example shows how to validate an entered email address. An email address must contain at least a ‘@’ sign and a dot (.). Also, the ‘@’ must not be the first character of the email address, and the last dot must at least be one character after the ‘@’ sign.
Example
尝试以下代码进行电子邮件验证。
Try the following code for email validation.
<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 创建一个复杂的动画,包括但不限于以下元素:
You can use JavaScript to create a complex animation having, but not limited to, the following elements −
-
Fireworks
-
Fade Effect
-
Roll-in or Roll-out
-
Page-in or Page-out
-
Object movements
你可能对现有的基于 JavaScript 的动画库感兴趣: Script.Aculo.us 。
You might be interested in existing JavaScript based animation library: Script.Aculo.us.
本教程提供了如何使用 JavaScript 来创建动画的基本理解。
This tutorial provides a basic understanding of how to use JavaScript to create an animation.
JavaScript 可用于移动一些 DOM 元素(<img/>、<div> 或任何其他 HTML 元素)在页面上依据由逻辑方程式或函数确定的某种样式进行移动。
JavaScript can be used to move a number of DOM elements (<img />, <div> or any other HTML element) around the page according to some sort of pattern determined by a logical equation or function.
JavaScript 提供了以下两个函数,在动画程序中经常使用。
JavaScript provides the following two functions to be frequently used in animation programs.
-
setTimeout( function, duration) − This function calls function after duration milliseconds from now.
-
setInterval(function, duration) − This function calls function after every duration milliseconds.
-
clearTimeout(setTimeout_variable) − This function calls clears any timer set by the setTimeout() functions.
JavaScript 还可以设置 DOM 对象的多个属性,包括它在屏幕上的位置。你可以设置对象的上和左属性,以将其定位在屏幕上的任何位置。下面是它的语法。
JavaScript can also set a number of attributes of a DOM object including its position on the screen. You can set top and left attribute of an object to position it anywhere on the screen. Here is its syntax.
// 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 方法。
So let’s implement one simple animation using DOM object properties and JavaScript functions as follows. The following list contains different DOM methods.
-
We are using the JavaScript function getElementById() to get a DOM object and then assigning it to a global variable imgObj.
-
We have defined an initialization function init() to initialize imgObj where we have set its position and left attributes.
-
We are calling initialization function at the time of window load.
-
Finally, we are calling moveRight() function to increase the left distance by 10 pixels. You could also set it to a negative value to move it to the left side.
Example
尝试以下示例。
Try the following 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>
Automated Animation
在以上示例中,我们看到了图像如何随着每次点击向右移动。我们可以通过使用 JavaScript 函数 setTimeout() 自动化此过程,如下所示 −
In the above example, we saw how an image moves to right with every click. We can automate this process by using the JavaScript function setTimeout() as follows −
这里我们添加了更多方法。所以,让我们看看这里有哪些新增内容 −
Here we have added more methods. So let’s see what is new here −
-
The moveRight() function is calling setTimeout() function to set the position of imgObj.
-
We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position.
Example
尝试以下示例代码。
Try the following example code.
<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
这是一个显示鼠标事件图像翻转效果的简单示例。
Here is a simple example showing image rollover with a mouse event.
让我们看看我们在以下示例中使用了什么 −
Let’s see what we are using in the following example −
-
At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed.
-
The Image() constructor creates and preloads a new image object called image1.
-
The src property is assigned the name of the external image file called /images/html.gif.
-
Similarly, we have created image2 object and assigned /images/http.gif in this object.
-
The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image.
-
The onMouseOver event handler is triggered when the user’s mouse moves onto the link, and the onMouseOut event handler is triggered when the user’s mouse moves away from the link (image).
-
When the mouse moves over the image, the HTTP image changes from the first image to the second one. When the mouse is moved away from the image, the original image is displayed.
-
When the mouse is moved away from the link, the initial image html.gif will reappear on the screen.
<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支持。
The JavaScript navigator object includes a child object called plugins. This object is an array, with one entry for each plug-in installed on the browser. The navigator.plugins object is supported only by Netscape, Firefox, and Mozilla only.
Example
下面是一个示例,它展示了如何列出你的浏览器中安装的所有插件:
Here is an example that shows how to list down all the plug-on installed in your browser −
<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>
Checking for Plug-Ins
每个插件在数组中都有一个条目。每个条目有以下的属性:
Each plug-in has an entry in the array. Each entry has the following properties −
-
name − is the name of the plug-in.
-
filename − is the executable file that was loaded to install the plug-in.
-
description − is a description of the plug-in, supplied by the developer.
-
mimeTypes − is an array with one entry for each MIME type supported by the plug-in.
你可以在脚本中使用这些属性来找出已安装的插件,然后使用JavaScript播放适当的多媒体文件。看看下面的示例。
You can use these properties in a script to find out the installed plug-ins, and then using JavaScript, you can play appropriate multimedia file. Take a look at the following example.
<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>
Controlling Multimedia
让我们举一个在几乎所有浏览器中都适用的真实示例:
Let us take one real example which works in almost all the browsers −
<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>
JavaScript - Debugging
开发者经常在编码时会犯错误。程序或脚本中的错误称为` bug `。
Every now and then, developers commit mistakes while coding. A mistake in a program or a script is referred to as a bug.
查找和修复错误的过程被称为` debugging `,是开发过程中的正常部分。本部分涵盖了可以帮助你完成调试任务的工具和技术。
The process of finding and fixing bugs is called debugging and is a normal part of the development process. This section covers tools and techniques that can help you with debugging tasks..
Error Messages in IE
追踪错误的最基本的方法是启用浏览器中的错误信息。默认情况下,当页面上发生错误时,Internet Explorer会在状态栏中显示一个错误图标。
The most basic way to track down errors is by turning on error information in your browser. By default, Internet Explorer shows an error icon in the status bar when an error occurs on the page.
双击此图标,你将进入一个显示有关所发生具体错误的信息的对话框。
Double-clicking this icon takes you to a dialog box showing information about the specific error that occurred.
由于此图标很容易被人忽略,因此Internet Explorer为你提供了在发生错误时自动显示“错误”对话框的选项。
Since this icon is easy to overlook, Internet Explorer gives you the option to automatically show the Error dialog box whenever an error occurs.
要启用此选项,请选中` Tools → Internet Options → Advanced tab. ,然后最终选中
"Display a Notification About Every Script Error" `框,如下所示:
To enable this option, select Tools → Internet Options → Advanced tab. and then finally check the "Display a Notification About Every Script Error" box option as shown below −
Error Messages in Firefox or Mozilla
像 Firefox、Netscape 以及 Mozilla 等其他浏览器会将错误信息发送到一个名为 JavaScript Console 或 Error Consol 的特殊窗口。要查看控制台,请选择 Tools → Error Consol or Web Development 。
Other browsers like Firefox, Netscape, and Mozilla send error messages to a special window called the JavaScript Console or Error Consol. To view the console, select Tools → Error Consol or Web Development.
不幸的是,由于这些浏览器在发生错误时不会给出任何视觉指示,因此你必须保持控制台打开,并在脚本执行时注意错误。
Unfortunately, since these browsers give no visual indication when an error occurs, you must keep the Console open and watch for errors as your script executes.
Error Notifications
控制台中显示的或通过 Internet Explorer 对话框显示的错误通知都是语法和运行时错误造成的。这些错误通知包含发生错误的行号。
Error notifications that show up on Console or through Internet Explorer dialog boxes are the result of both syntax and runtime errors. These error notification include the line number at which the error occurred.
如果你使用的是 Firefox,则可以单击错误控制台中提供的错误以转到脚本中出现错误的确切行。
If you are using Firefox, then you can click on the error available in the error console to go to the exact line in the script having error.
How to debug a Script
有多种方法可以调试 JavaScript −
There are various ways to debug your JavaScript −
Use a JavaScript Validator
检查 JavaScript 代码中是否存在异常错误的一种方法是通过程序来运行它,以确保它是有效的,并且它遵循该语言的官方语法规则。这些程序称为 validating parsers 或简称 validators ,通常附带商业 HTML 和 JavaScript 编辑器。
One way to check your JavaScript code for strange bugs is to run it through a program that checks it to make sure it is valid and that it follows the official syntax rules of the language. These programs are called validating parsers or just validators for short, and often come with commercial HTML and JavaScript editors.
JavaScript 最方便的验证器是 Douglas Crockford 的 JavaScript Lint,该验证器可以在 Douglas Crockford’s JavaScript Lint 免费获得。
The most convenient validator for JavaScript is Douglas Crockford’s JavaScript Lint, which is available for free at Douglas Crockford’s JavaScript Lint.
只需访问该网页,将 JavaScript(仅 JavaScript)代码粘贴到提供的文本区域中,然后单击 jslint 按钮。此程序将解析 JavaScript 代码,确保所有变量和函数定义都遵循正确的语法。它还将检查 JavaScript 语句,例如 if 和 while, 以确保它们也遵循正确的格式
Simply visit that web page, paste your JavaScript (Only JavaScript) code into the text area provided, and click the jslint button. This program will parse through your JavaScript code, ensuring that all the variable and function definitions follow the correct syntax. It will also check JavaScript statements, such as if and while, to ensure they too follow the correct format
Add Debugging Code to Your Programs
你可以在程序中使用 alert() 或 document.write() 方法来调试代码。例如,你可以编写类似以下内容的东西 −
You can use the alert() or document.write() methods in your program to debug your code. For example, you might write something as follows −
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() 出现的顺序和内容,你可以非常容易地检查程序的运行状况。
By examining the content and order of the alert() as they appear, you can examine the health of your program very easily.
Use a JavaScript Debugger
调试器是一种将脚本执行的所有方面置于程序员控制之下的应用程序。调试器通过允许你检查和设置值以及控制执行流的接口,提供了对脚本状态的精细控制。
A debugger is an application that places all aspects of script execution under the control of the programmer. Debuggers provide fine-grained control over the state of the script through an interface that allows you to examine and set values as well as control the flow of execution.
将脚本加载到调试器中后,可以一次运行一行,或者指示在某些断点处停止。中止执行后,程序员可以检查脚本及其变量的状态,以确定是否有问题。你还可以观察变量的值的变化。
Once a script has been loaded into a debugger, it can be run one line at a time or instructed to halt at certain breakpoints. Once execution is halted, the programmer can examine the state of the script and its variables in order to determine if something is amiss. You can also watch variables for changes in their values.
最新的 Mozilla JavaScript 调试器(代号 Venkman)适用于 Mozilla 和 Netscape 浏览器,可以在链接:https://www.hacksrus.com/ ginda/venkman[http://www.hacksrus.com/ ginda/venkman] 下载
The latest version of the Mozilla JavaScript Debugger (code-named Venkman) for both Mozilla and Netscape browsers can be downloaded at http://www.hacksrus.com/ginda/venkman
Useful Tips for Developers
你可以记住以下提示以减少脚本中的错误数量并简化调试过程 −
You can keep the following tips in mind to reduce the number of errors in your scripts and simplify the debugging process −
-
Use plenty of comments. Comments enable you to explain why you wrote the script the way you did and to explain particularly difficult sections of code.
-
Always use indentation to make your code easy to read. Indenting statements also makes it easier for you to match up beginning and ending tags, curly braces, and other HTML and script elements.
-
Write modular code. Whenever possible, group your statements into functions. Functions let you group related statements, and test and reuse portions of code with minimal effort.
-
Be consistent in the way you name your variables and functions. Try using names that are long enough to be meaningful and that describe the contents of the variable or the purpose of the function.
-
Use consistent syntax when naming variables and functions. In other words, keep them all lowercase or all uppercase; if you prefer Camel-Back notation, use it consistently.
-
Test long scripts in a modular fashion. In other words, do not try to write the entire script before testing any portion of it. Write a piece and get it to work before adding the next portion of code.
-
Use descriptive variable and function names and avoid using single-character names.
-
Watch your quotation marks. Remember that quotation marks are used in pairs around strings and that both quotation marks must be of the same style (either single or double).
-
Watch your equal signs. You should not used a single = for comparison purpose.
-
Declare variables explicitly using the var keyword.
JavaScript - Image Map
你可以使用 JavaScript 来创建客户端图像映射。客户端图像映射是由 <img /> 标记的 usemap 属性启用的,并由特殊的 <map> 和 <area> 扩展标记定义。
You can use JavaScript to create client-side image map. Client-side image maps are enabled by the usemap attribute for the <img /> tag and defined by special <map> and <area> extension tags.
构成映射的图像通过 <img /> 元素插入页面与平时一样,除了它带有称为 usemap 的额外属性。usemap 属性的值是 <map> 元素上 name 属性值,你即将遇到,前面有一个井号或磅号。
The image that is going to form the map is inserted into the page using the <img /> element as normal, except that it carries an extra attribute called usemap. The value of the usemap attribute is the value of the name attribute on the <map> element, which you are about to meet, preceded by a pound or hash sign.
<map> 元素实际创建图像的映射,通常紧跟在 <img /> 元素之后。它充当 <area /> 元素的容器,<area /> 元素实际定义可点击热点。<map> 元素只有一个属性, name 属性,它是标识映射的名称。这是 <img /> 元素知道要使用哪个 <map> 元素的方式。
The <map> element actually creates the map for the image and usually follows directly after the <img /> element. It acts as a container for the <area /> elements that actually define the clickable hotspots. The <map> element carries only one attribute, the name attribute, which is the name that identifies the map. This is how the <img /> element knows which <map> element to use.
<area> 元素指定形状和坐标,它们定义每个可点击热点的边界。
The <area> element specifies the shape and the coordinates that define the boundaries of each clickable hotspot.
以下代码结合了图像映射和 JavaScript,当鼠标移动到图像的不同部分时,在文本框中生成一条消息。
The following code combines imagemaps and JavaScript to produce a message in a text box when the mouse is moved over different parts of an image.
<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>
JavaScript - Browsers Compatibility
为了以预期的方式处理每个浏览器,重要的是了解不同浏览器之间的差异。因此,了解您的网页正在哪个浏览器中运行非常重要。
It is important to understand the differences between different browsers in order to handle each in the way it is expected. So it is important to know which browser your web page is running in.
用内置 navigator 对象获取您的网页当前正在运行的浏览器信息。
To get information about the browser your webpage is currently running in, use the built-in navigator object.
Navigator Properties
有一些与 Navigator 相关的属性,您可以在您的网页中使用。以下是每个属性的名称和说明。
There are several Navigator related properties that you can use in your Web page. The following is a list of the names and descriptions of each.
Sr.No. |
Property & Description |
1 |
appCodeName This property is a string that contains the code name of the browser, Netscape for Netscape and Microsoft Internet Explorer for Internet Explorer. |
2 |
appVersion This property is a string that contains the version of the browser as well as other useful information such as its language and compatibility. |
3 |
language This property contains the two-letter abbreviation for the language that is used by the browser. Netscape only. |
4 |
mimTypes[] This property is an array that contains all MIME types supported by the client. Netscape only. |
5 |
platform[] This property is a string that contains the platform for which the browser was compiled."Win32" for 32-bit Windows operating systems |
6 |
plugins[] This property is an array containing all the plug-ins that have been installed on the client. Netscape only. |
7 |
userAgent[] This property is a string that contains the code name and version of the browser. This value is sent to the originating server to identify the client. |
Navigator Methods
有一些特定的 Navigator 方法。以下是它们名称和说明的列表。
There are several Navigator-specific methods. Here is a list of their names and descriptions.
Sr.No. |
Description |
1 |
javaEnabled() This method determines if JavaScript is enabled in the client. If JavaScript is enabled, this method returns true; otherwise, it returns false. |
2 |
plugings.refresh This method makes newly installed plug-ins available and populates the plugins array with all new plug-in names. Netscape only. |
3 |
preference(name,value) This method allows a signed script to get and set some Netscape preferences. If the second parameter is omitted, this method will return the value of the specified preference; otherwise, it sets the value. Netscape only. |
4 |
taintEnabled() This method returns true if data tainting is enabled; false otherwise. |
Browser Detection
有一个简单的 JavaScript,它可以用来找出浏览器的名称,然后可以向用户提供相应 HTML 页面。
There is a simple JavaScript which can be used to find out the name of a browser and then accordingly an HTML page can be served to the user.
<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>