Internet Technologies 简明教程
JavaScript
Introduction
JavaScript 是具有面向对象功能的轻量级解释型编程语言,它允许你在静态 HTML 页面中构建交互性。
JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages.
Key Points
Key Points
-
It is Lightweight, interpreted programming language.
-
It is designed for creating network-centric applications.
-
It is complementary to and integrated with Java.
-
It is complementary to and integrated with HTML
-
It is an open and cross-platform
JavaScript Statements
JavaScript 语句是用于告诉浏览器执行哪些操作的命令。语句以分号 (;) 分隔。
JavaScript statements are the commands to tell the browser to what action to perform. Statements are separated by semicolon (;).
JavaScript 语句示例:
Example of JavaScript statement:
document.getElementById("demo").innerHTML = "Welcome";
下表显示了各种 JavaScript 语句 −
Following table shows the various JavaScript Statements −
Sr.No. |
Statement |
Description |
1. |
switch case |
A block of statements in which execution of code depends upon different cases. 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. |
2. |
If else |
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally. |
3. |
While |
The purpose of a while loop is to execute a statement or code block repeatedly as long as expression is true. Once expression becomes false, the loop will be exited. |
4. |
do while |
Block of statements that are executed at least once and continues to be executed while condition is true. |
5. |
for |
Same as while but initialization, condition and increment/decrement is done in the same line. |
6. |
for in |
This loop is used to loop through an object’s properties. |
7. |
continue |
The continue statement tells the interpreter to immediately start the next iteration of the loop and skip remaining code block. |
8. |
break |
The break statement is used to exit a loop early, breaking out of the enclosing curly braces. |
9. |
function |
A function is a group of reusable code which can be called anywhere in your programme. The keyword function is used to declare a function. |
10. |
return |
Return statement is used to return a value from a function. |
11. |
var |
Used to declare a variable. |
12. |
try |
A block of statements on which error handling is implemented. |
13. |
catch |
A block of statements that are executed when an error occur. |
14. |
throw |
Used to throw an error. |
JavaScript Comments
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
<script language="javascript" type="text/javascript">
<!--
// this is a comment. It is similar to comments in C++
/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
<script>
JavaScript variable
变量称为用于存储信息的命名容器。我们可以将数据放入这些容器中,然后通过对容器命名来引用数据。
Variables are referred as named containers for storing information. We can place data into these containers and then refer to the data simply by naming the container.
Rules to declare variable in JavaScript
以下是声明 JavaScript 中变量时必须遵循的重要规则。
Here are the important rules that must be followed while declaring a variable in JavaScript.
-
In JavaScript variable names are case sensitive i.e. a is different from A.
-
Variable name can only be started with a underscore ( _ ) or a letter (from a to z or A to Z), or dollar ( $ ) sign.
-
Numbers (0 to 9) can only be used after a letter.
-
No other special character is allowed in variable name.
在 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, age;
//-->
</script>
变量可以在声明时或声明后进行初始化,如下所示 −
Variables can be initialized at time of declaration or after declaration as follows −
<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Javascript Data Type
有两种数据类型,如下所示 −
There are two kinds of data types as mentioned below −
-
Primitive Data Type
-
Non Primitive Data Type
下表描述了 javaScript 中可用的 Primitive Data Types
The following table describes Primitive Data Types available in javaScript
Sr.No. |
Datatype Description |
1. |
*String*Can contain groups of character as single value. It is represented in double quotes.E.g. var x= “tutorial”. |
2. |
*Numbers*Contains the numbers with or without decimal. E.g. var x=44, y=44.56; |
3. |
*Booleans*Contain only two values either true or false. E.g. var x=true, y= false. |
4. |
*Undefined*Variable with no value is called Undefined. E.g. var x; |
5. |
*Null*If we assign null to a variable, it becomes empty. E.g. var x=null; |
下表描述了 JavaScript 中的 Non-Primitive Data Types
The following table describes Non-Primitive Data Types in javaScript
Sr.No. |
Datatype Description |
1. |
Array Can contain groups of values of same type. E.g. var x={1,2,3,55}; |
2. |
Objects Objects are stored in property and value pair. E.g. var rectangle = { length: 5, breadth: 3}; |
JavaScript Functions
函数是一组可重用语句(代码),可以在程序中任何位置调用。在 JavaScript 中,function 关键字用于声明或定义函数。
Function is a group of reusable statements (Code) that can be called any where in a program. In javascript function keyword is used to declare or define a function.
Key Points
Key Points
-
To define a function use function keyword followed by functionname, followed by parentheses ().
-
In parenthesis, we define parameters or attributes.
-
The group of reusabe statements (code) is enclosed in curly braces {}. This code is executed whenever function is called.
Syntax
Syntax
function functionname (p1, p2) {
function coding…
}
JavaScript Operators
运算符用于对一个、两个或更多操作数执行运算。运算符由符号表示,例如 +, =, *, % 等。以下是 JavaScript 支持的运算符 −
Operators are used to perform operation on one, two or more operands. Operator is represented by a symbol such as +, =, *, % etc. Following are the operators supported by javascript −
-
Arithmetic Operators
-
Comparison Operators
-
Logical (or Relational) Operators
-
Assignment Operators
-
Conditional (or ternary) Operators
-
Arithmetic Operators
Arithmatic Operators
下表显示了 JavaScript 支持的所有算术运算符 −
Following table shows all the arithmetic operators supported by javascript −
Operator |
Description |
Example |
+ |
Add two operands. |
10 + 10 will give 20 |
- |
Subtract second operand from the first. |
10 – 10 will give 0 |
* |
Multiply two operands. |
10 * 30 will give 300 |
/ |
Divide numerator by denominator |
10/10 will give 1 |
% |
It is called modulus operator and gives remainder of the division. |
10 % 10 will give 0 |
++ |
Increment operator, increases integer value by one |
10 ++ will give 11 |
— |
Decrement operator, decreases integer value by one |
10 – will give 9 |
Comparison Operators
下表显示了 javascript 支持的所有比较运算符 −
Following table shows all the comparison operators supported by javascript −
Operator |
Description |
Example |
== |
Checks if values of two operands are equal or not, If yes then condition becomes true. |
10 == 10 will give true |
!= |
Not Equal to operator Checks if the value of two operands is equal or not, if values are not equal then condition becomes true. |
10 !=10 will give false |
> |
Greater Than operator Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. |
20 > 10 will give true |
< |
Less than operator Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. |
10 < 20 will give true |
>= |
Greater than or equal to operator Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. |
10 >=20 will give false |
⇐ |
Less than or equal to operator Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. |
10 ⇐20 will give true. |
Logical Operators
下表显示了 javascript 支持的所有逻辑运算符 −
Following table shows all the logical operators supported by javascript −
Operator |
Description |
Example |
&& |
Logical AND operator returns true if both operands are non zero. |
10 && 10 will give true. |
Logical OR operator returns true If any of the operand is non zero |
10 |
|
0 will give true. |
! |
Logical NOT operator complements the logical state of its operand. |
Assignment Operators
下表显示了 JavaScript 支持的所有赋值运算符 −
Following table shows all the assignment operators supported by javascript −
Operator |
Description |
Example |
= |
Simple Assignment operator Assigns values from right side operands to left side operand. |
C = A + B will assign value of A + B into C |
+= |
Add AND assignment operator It adds right operand to the left operand and assign the result to left operand |
C += A is equivalent to C = C + A |
-= |
Subtract AND assignment operator It subtracts right operand from the left operand and assign the result to left operand |
C -= A is equivalent to C = C - A |
*= |
Multiply AND assignment operator It multiplies right operand with the left operand and assign the result to left operand |
C *= A is equivalent to C = C * A |
/= |
Divide AND assignment operator It divides left operand with the right operand and assign the result to left operand |
C /= A is equivalent to C = C / A |
%= |
Modulus AND assignment operator Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand |
C %= A is equivalent to C = C % A |
Control Structure
控制结构实际上控制程序执行的流程。以下是 JavaScript 支持的几个控制结构。
Control structure actually controls the flow of execution of a program. Following are the several control structure supported by javascript.
-
if … else
-
switch case
-
do while loop
-
while loop
-
for loop
If … else
if 语句是基本的控制语句,它允许 JavaScript 做出决策和有条件地执行语句。
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.
Syntax
Syntax
if (expression){
Statement(s) to be executed if expression is true
}
Example
<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
Switch case
switch 语句的基本语法是给予一个表达式进行求值,并根据表达式的值执行多个不同的语句。解释器检查每个情况与表达式的值,直到找到匹配项。如果没有任何匹配项,将使用默认条件。
The basic syntax of the 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.
Syntax
Syntax
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
Example
<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>
Do while Loop
do…while 循环类似于 while 循环,不同之处在于条件检查在循环结束时发生。这意味着该循环将始终执行至少一次,即使条件为假。
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
Syntax
do{
Statement(s) to be executed;
} while (expression);
Example
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br/>");
do{
document.write("Current Count : " + count + "<br/>");
count++;
}while (count < 0);
document.write("Loop stopped!");
//-->
</script>
这将生成以下结果:
This will produce following result −
Starting Loop
Current Count : 0
Loop stopped!
While Loop
while 循环的用途是只要表达式为 true 就重复执行一条语句或代码块。一旦表达式变为 false,则循环将退出。
The purpose of a while loop is to execute a statement or code block repeatedly as long as expression is true. Once expression becomes false, the loop will be exited.
Syntax
Syntax
while (expression){
Statement(s) to be executed if expression is true
}
Example
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br/>");
while (count < 10){
document.write("Current Count : " + count + "<br/>");
count++;
}
document.write("Loop stopped!");
//-->
</script>
这将生成以下结果:
This will produce following result −
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
For Loop
for 循环是最简洁的循环形式,包括以下三个重要部分 −
The for loop is the most compact form of looping and 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 the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out.
-
The iteration statement where you can increase or decrease your counter.
Syntax
Syntax
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true
}
示例
Example
<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>
这将产生与 while 循环类似的以下结果 −
This will produce following result which is similar to while loop −
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Creating Sample Program
以下是展示时间的示例程序,当我们单击按钮时。
Following is the sample program that shows time, when we click in button.
<html>
<body>
<button onclick="this.innerHTML=Date()">The time is?</button>
<p>Click to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}</script>
<p id="demo"></p>
</script>
</body>
</html>
Output