JavaScript Syntax
- Statements
- Variable and arrays
- Operators
- Conditional statements and looping statements
- Fuctions and objects
Statements
用 ;
结尾
Variable
- var
- 大小写敏感
- 字母、数字、下划线、$
- number、string、array
Arrays
使用 Array(4)
关键字声明一个包含4个元素的数组
var beatles = Arrays(4);
声明一个不指定元素个数的数组
var beatles = Array();
给数组赋值
方法 1:
var beatles = Array(4);
beatles[0] = 'John';
beatles[1] = 'Paul';
beatles[2] = 'George';
beatles[3] = 'Ringo';
方法 2:
var beatles = Array('John', 'Paul', 'George', 'Ringo');
方法 3:
var beatles = ['John', 'Paul', 'George', 'Ringo'];
数组的元素类型没有限制
var years = [1940, 1941, 1942, 1943];
var lennon = ['John', 1940, false];
beatles[0] = lennon; // 甚至数组里可以放入数组当作元素
Associative arrays
不推荐使用,应该使用 Object
var lennon = Array();
lennon['name'] = 'John';
lennon['year'] = 1940;
lennon['living'] = false;
Object
var lennon = Object();
lennon.name = 'John';
lennon.year = 1940;
lennon.living = false;
也可以这么创建一个对象
var lennon = {
name: 'John',
year: 1940,
living: false
};
Arithmetic operators
+
-
*
/
?
%
()
Conditional statements
if (condition) {
statements;
}
Comparison operators
>
<
>=
<=
==
!=
===
!==
Logical operator
&&
||
Looping statement
while loop
while (codition) {
statments;
}
do...while loop
do {
statements;
} while (condition);
for loop
for (initial codition; test condition; alter condition) {
statemetns;
}
Functions
function name(arguments) {
statements;
}
Variable scope
用 var
区分变量的作用域
Object
Object 由两部分组成
- 属性
- 方法
所谓属性
A property is a variable belonging to an object.
所谓方法
A method is a function that the object can invoke.
调用方式
Object.property
Object.method()