《Javacript DOM 程式設計藝術》筆記(一)JavaScript Syntax

weixin_34320159發表於2018-05-26

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()

相關文章