沒想到轉眼就要30天了,先容我將進度快轉到第八章XD
第八章的主題是除錯
因為 js 本身為 Dynamic Typing language
, weakly typed language
像是:
// 宣告變數時不需要定義 type
let name = 'Mathrew';
name = 123;
let someVal = 3; // number
let someString = 'Glad to see you.' // string
console.log(someString + someVal); // "Glad to see you.3" 會自動將 number 轉換型別為 string
這使 js 很有彈性但也同時導致容易產生錯誤
這時候有幾個方法可以有效去減少錯誤或者追蹤錯誤從哪裡產生
請使用嚴格模式
用法相當簡單,直接在 code 頂端添加 use strict;
即可
舉例來說
假設不小心忘記在 for loop 建立初始的變數..
let shoppingList = ["notebook", "pen", "eraser"];
function loopSth(arr) {
// forget to declare variable with let
for (v of arr) {
console.log(`I need to buy ${v}.`);
}
}
loopSth(shoppingList); // js 會幫你建立名為 v 的變數,所以是可以被執行的..
但如果使用了嚴格模式..
"use strict";
let shoppingList = ["notebook", "pen", "eraser"];
function loopSth(arr) {
// forget to declare variable with let
for (v of arr) {
console.log(`I need to buy ${v}.`);
}
}
loopSth(shoppingList); // Uncaught ReferenceError: v is not defined
use simple returns for simple checks, and use structured objects for complex or unavoidable failures
null
, undefined
等 falsy value當 function 執行時僅需對 parameter 做簡單檢查,或錯誤顯而易見的情況
可直接回傳 falsy value
舉例來說 promptName 僅對 name 做檢查,不符合型態則直接回傳錯誤值
function promptName(name){
if (typeof name!== string || !name){
return false;
}else{
console.log(`user name is :${name}`)
}
}
當 function 執行時需明確區分成功與失敗的情況,或可能有多種導致程式有異常的情況
則需要回傳帶有更詳細錯誤訊息的 object,有助於知道到底是程式是哪個階段失敗而產生異常
舉例來說
像是 fetch data from api
function fetchUserData(id) {
if (id <= 0) {
// Failure 1: Invalid Parameter
return { error: 'Invalid ID: Must be positive.' };
}
// ... network code ...
if (response.status === 404) {
// Failure 2: Resource Not Found
return { error: 'User not found.' };
}
// Success
return { user: data };
}