1. 程式人生 > 實用技巧 >二、通過例項學習JavaScript語法

二、通過例項學習JavaScript語法

3、資料型別

3.1、字串

3.2、陣列

3.3、物件

var person = {
  firstName: "Bill",
  lastName : "Gates",
  id       : 678,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
console.log(person.firstname);
console.log(person.fullName());

3.4、流程控制

let age = 3;
if (age > 3) {
    alert("大於3歲了");
} else {
    alert("不到3歲");
}

迴圈:

while (age < 100) {
    age++;
    console.log(age);
}
for (let i = 0; i < 100; i++) {
    console.log(i);
}

陣列迴圈

var arr = [1, 4, 3];
for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}
for (let num of arr) {
    console.log(num)
}

forEach 迴圈

let arr = [2, 3, 4];
arr.forEach(function (value) {
    console.log(value);
});

3.5、Map 和 Set

ES6 新特性

Map:

let map = new Map([['tom', 100], ['jack', 90]]);
let number = map.get('tom');
console.log(number);
map.set("admin", 10000);
map.delete('admin');

Set:

let set = new Set([1, 2, 3, 4, 1, 1]);
set.add(5);
set.delete(5);
let has = set.has(4);
console.log(has);

3.6、iterator迭代器

ES6 新特性

var arr = [1, 4, 3];
for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}
for (let num of arr) {
    console.log(num)
}

遍歷Map

for (let mapElement of map) {
    console.log(mapElement);
}

遍歷Set

for (let number1 of set) {
    console.log(number1);
}

4、函式

4.1、函式定義及呼叫

方式一

function abs(x) {
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}
let x = abs(10);

方式二

let abs = function (x) {
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}
let x = abs(-99);

不傳參

let abs = function (x) {
    if (typeof x !== 'number') {
        throw 'not a number';
    }
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}

arguments: 獲取所有引數

let abs = function (x) {
    for (let i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);

    }
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}
let x = abs(-99, -11, 1, 2, 3);

rest引數,獲取除宣告之外的引數

console.log("a=>" + a);
console.log("b=>" + b);
for (let restElement of rest) {
    console.log(restElement);
}

4.2、變數的作用域

  1. 區域性變數
  2. 全域性變數
  3. 常量 const

4.3、方法

  1. 定義在物件內部
  2. 定義在外部
  3. 呼叫的時候要加括號(如果在物件內部呼叫,只寫名字)

5、內部物件

標準物件

typeof 123
"number"
typeof "123"
"string"
typeof true
"boolean"
typeof NaN
"number"
typeof []
"object"
typeof {}
"object"
typeof Math.abs
"function"
typeof undefined
"undefined"

5.1、Date

let now = new Date();
now.getFullYear()
now.getMonth()
now.getDate() // 日
now.getDay() // 周幾
now.getHours()
now.getMinutes();
now.getSeconds();

now.getTime(); // 時間戳

5.2、JSON

  • 物件都用{}
  • 陣列都用[]
  • 所有的鍵值對都用 key : value
let user = {
    "name": "faddei",
    "age": 24,
    "sex": "male"

};
let str = JSON.stringify(user); // 將物件轉換成字串,'{"name":"faddei","age":24,"sex":"male"}'

let obj = JSON.parse('"{"name":"faddei","age":24,"sex":"male"}"'); // 將字串轉換成物件