Javascript 简明教程
JavaScript - Syntax
JavaScript Syntax
JavaScript 语法包含一组规则,用来定义如何构建 JavaScript 代码。可以通过 JavaScript 语句来实现 JavaScript,这些语句被放置在网页中的 <script>… </script> HTML 标记中。
JavaScript syntax comprises a set of rules that define how to construct a JavaScript code. 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>
-
*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 has become default lannguage in HTML5, and modern browsers, so now adding type is not required.
因此,你的 JavaScript 代码段看起来像 −
So your JavaScript segment will look like −
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>
Your First JavaScript Code
让我们使用一个示例,打印出 “Hello World”。我们调用 document.write 方法,它将字符串写入到我们的 HTML 文档中。此方法可用于写入文本、HTML 或者两者。查看以下代码 −
Let us take a sample example to print out "Hello World". We call document.write method which writes a string into our HTML document. This method can be used to write text, HTML, or both. Take a look at the following code −
<html>
<head>
<title> Your first JavaScript program </title>
<head>
<body>
<script language = "javascript" type = "text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
此代码将产生以下结果 −
This code will produce the following result −
Hello World!
JavaScript Values
在 JavaScript 中,你可以使用两种类型的值。
In JavaScript, you can have two types of values.
-
Fixed values (Literals)
-
Variables (Dynamic values)
JavaScript Literals
在下面的代码中,10 是数字文字,‘Hello’ 是字符串文字。
In the below code, 10 is a Number literal and ‘Hello’ is a string literal.
<html>
<body>
<script>
document.write(10); // Number Literal
document.write("<br />"); // To add line-break
document.write("Hello"); // String Literal
</script>
</body>
</html>
此代码将产生以下结果 −
This code will produce the following result −
10
Hello
JavaScript Variables
在 JavaScript 中,变量用于存储动态数据。
In JavaScript, variables are used to store the dynamic data.
你可以使用下面的关键字来定义 JavaScript 中的变量。
You can use the below keyword to define variables in JavaScript.
-
var
-
let
-
const
你可以使用赋值运算符(等于符号)来给变量赋值。
You can use the assignment operator (equal sign) to assign values to the variable.
在下面的代码中,变量 a 包含数字值,并且变量 b 包含文本(字符串)。
In the below code, variable a contains the numeric value, and variable b contains the text (string).
<html>
<body>
<script>
let a = 5; // Variable Declaration
document.write(a); // Using variable
document.write("<br>");
let b = "One";
document.write(b);
</script>
</body>
</html>
此代码将产生以下结果 −
This code will produce the following result −
5
One
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>
var1 = 10
var2 = 20
</script>
但是,如果按如下方式格式化为单行,则你必须使用分号 −
But when formatted in a single line as follows, you must use semicolons −
<script>
var1 = 10; var2 = 20;
</script>
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.
在下面的代码中,我们比较了字符串“time”和“Time”,并返回 false。
In the code below, we compare the ‘time’ and ‘Time’ strings, which returns false.
<html>
<body>
<script>
let a = "time";
let b = "Time";
document.write("a == b? " + (a == b));
</script>
</body>
</html>
此代码将产生以下结果 −
This code will produce the following result −
a == b? false
JavaScript and Camel Case
-
*Pascal Case *− We can create variables like SmartWatch, MobileDevice, WebDrive, etc. It represents the upper camel case string.
-
*Lower Camel Case *− JavaScript allows developers to use variable names and expression names like smartwatch, mobileDevice, webDriver, etc. Here the first character is in lowercase.
-
*Underscore *− We can use underscore while declaring variables like smart_watch, mobile_device, web_driver, etc.
JavaScript Keywords
JavaScript 包含多个关键字,可以用于特定任务。例如,function 关键字可用于定义函数。let、var 和 const 关键字可用于定义变量。
JavaScript contains multiple keywords which we can use for a particular task. For example, the function keyword can be used to define the function. The let, var, and const keywords can be used to define variables.
让我们通过下面的例子理解关键字的用法。
Let’s understand the use of the keyword via the example below.
Example
在这个例子中,我们使用 function 关键字来定义函数。我们在函数内部使用 var 关键字来定义 sum 变量。
In this example, we used the function keyword to define the function. We used the var keyword inside the function to define the sum variable.
此外,我们在函数外部使用 let 和 const 关键字来定义两个变量,并使用值对其进行初始化。之后,我们使用函数名称调用函数,并将变量作为参数传递。
Also, we used the let and const keywords outside the function to define two variables and initialize them with values. After that, we called the function using the function name and passed variables as an argument.
<html>
<body>
<script>
function getSum(first, second) {
var sum = first * second;
document.write("The product of " + first + " and " + second + " is " + sum);
}
let first = 3;
const second = 4;
getSum(first, second);
</script>
</body>
</html>
此代码将产生以下结果 −
This code will produce the following result −
The product of 3 and 4 is 12
JavaScript Identifiers
在 JavaScript 中,标识符是变量、函数、对象等的名字。
In JavaScript, identifiers are the name of variables, functions, objects, etc.
例如,p 是下面代码中的一个标识符。
For example, p is an identifier in the below code.
<script>
pet p = 90;
</script>
'test' 是下面代码中的一个标识符。
The 'test' is an identifier in the below code.
<script>
function test() {
}
</script>
以下是定义有效标识符需要遵循的规则。
Here are the rules which you should follow to define valid identifiers.
-
Identifiers should always start with the alphabetical characters (A-Z, a-z), $(dollar sign), or _ (underscore).
-
It shouldn’t start with digits or hyphens.
-
The identifier can also contain digits except for the start of it.
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 //-→.
Operators in JavaScript
JavaScript 包含各种算术、逻辑、按位等运算符。我们可以使用 JavaScript 中的任何运算符,如下示例所示。
JavaScript contains various arithmetic, logical, bitwise, etc. operators. We can use any operator in JavaScript, as shown in the example below.
Example
在这个示例中,我们定义了 var1 和 va2,并用数字值对其进行初始化。之后,我们使用 '*' 运算符获取 var1 和 var2 的乘法结果。
In this example, we have defined var1 and va2 and initialized them with number values. After that, we use the ‘*’ operator to get the multiplication result of var1 and var2.
<html>
<body>
<script>
var1 = 10
var2 = 20
var3 = var1 * var2;
var4 = 10 + 20;
document.write(var3, " " ,var4);
</script>
</body>
</html>
此代码将产生以下结果 −
This code will produce the following result −
200 30
通过这种方式,程序员可以使用操作数使用其他运算符。
In this way, programmers can use other operators with operands.
Expressions in JavaScript
你可以通过组合变量、值和运算符在 JavaScript 中创建表达式。
You can create expressions in JavaScript by combining the variable, values, and operators.
例如,下面的表达式添加两个数字。
For example, the below expression adds two numbers.
10 + 20;
下面的表达式将两个变量的值相乘。
The below expression multiplies the values of two variables.
a * b;
下面的表达式将变量 c 的值除以 2。
The below expression divides the value of variable c with 2.
c / 2;
Example
在下面的代码中,我们使用了赋值和算术表达式。
In the below code, we have used the assignment and arithmetic expressions.
<html>
<body>
<script>
let a = 10;
let b = 2;
let c = a; // Assigning a value of a to c. Assignment expression.
let d = a + b; // Adding a and b. Arithmetic expression.
let e = a - b; // Subtracting b from a.
document.write("c = " + c + "<br>");
document.write("d = " + d + "<br>");
document.write("e = " + e + "<br>");
</script>
</body>
</html>
此代码将产生以下结果 −
This code will produce the following result −
c = 10
d = 12
e = 8
我们将在接下来的章节中探索更多的表达式。
We will explore more expressions in the upcoming chapters.
JavaScript Character Set
JavaScript 包含一组 Unicode 字符。
JavaScript contains a set of Unicode characters.
Unicode 字符在文本中添加特殊字符,例如表情符号、符号等。
The Unicode characters add special characters like emoji, symbols, etc. in the text.
例如,下面的 Unicode 字符将显示向左箭头。
For example, the below Unicode character will display the left arrow.
&larr
下面的 Unicode 字符将显示 RS(卢比符号)符号。
The Below Unicode character will display the RS (Rupees sign) symbol.
8360
然而,有很多 JavaScript 语法需要我们学习,不可能在单一章节内学习完所有内容。因此,我们只在本节中学习了基本语法,以开始学习 JavaScript,我们将在接下来的章节中学习其他语法。
However, there are a lot of syntaxes of JavaScript we need to cover, and it is not possible to cover them in a single chapter. So, we have covered only basic syntax in this chapter to get started with JavaScript, and we will cover other syntaxes in upcoming chapters.