4.1
這一章的內容比較少,一共幾頁,而且多以文字敘述為主,挑自己覺得要用的地方寫一下。
首先,js是很少抱怨的語言,他很多情況下不管好的壞的都會接受而且不會報錯,我們在錯誤檢查的時候就會很頭痛。比如函數的參數可變,可接收幾乎任意多的參數,而且類型也不固定。你想傳入的該是一個整型,但是調用時你故意傳兩個字元型,它會默默忍受,不吱聲。
最簡單的錯誤就是語法錯誤了,給力的IDE基本能解決這個問題,(推薦:Webstorm)。還有執行階段錯誤,這個我瞭解不多,比如記憶體、網路、cpu等引起的錯誤。其它的錯誤就是程式員考慮不周造成的了,以前看過一本js的書,jsdom編程藝術,都說這本書不錯,我發現書中代碼有一個特點就是各種判斷,思維相當縝密。所以多琢磨,想出更多可能情況才能盡量減少錯誤的出現。
4.2 異常
異常的基本使用方法,不用多講,看下代碼就懂了.
function lastElement(array) { if (array.length > 0) { return array[array.length - 1]; } else { throw "cant get the return result"; } } function lastElementPlusTen(array) { return lastElement(array) + 10; } try{ document.write(lastElementPlusTen([])); } catch(error){ document.write("the error is: "+error); } var currentThings = "success"; function pressThing(things) { var tempThings = currentThings; try { currentThings = "too much operate: " + things; } finally { currentThings = tempThings; } } pressThing(1000); document.write(currentThings); try{ throw new Error("i am a error"); } catch(error) { document.write(error); }