
完整範例請參考
code 與 alph 的定義如下
1 2 3 4 5 6 7 8 9 10 11 12 | function Encrypt() { this .code = "abcdefghijklmnopqrstuvwxyz" .split( "" , 26); var i = this .code.length; while (i) { var j = parseInt(Math.random() * i); var k = this .code[--i]; this .code[i] = this .code[j]; this .code[j] = k; } this .alph = "abcdefghijklmnopqrstuvwxyz" .split( "" , 26); } |
這裡,我們直接將 this.code 用洗牌演算法攪亂順序,至於 this.alph 則在編碼、解碼時需要用到。
方法 (method) 則是定義在 Encrypt() 之外,我們打算建置四個方法,分別是顯示密碼表的 showCode() ,設定密碼表的 setCode() ,以及編碼的 toEncode() 與解碼的 toDecode() 。
showCode() 就是回傳密碼表字串 (string) 即可,但由於實際儲存密碼表的是陣列 (array) ,因此利用陣列的 join 法將所有元素以參數 (parameter) 空字串連結成一個字串,然後回傳這個字串
14 15 16 | Encrypt.prototype.showCode = function () { return this .code.join( "" ); } |
setCode() 主要是從 Cookie 取得儲存的密碼表後,用來重新設定 Encrypt 物件的 code 屬性,由於儲存的會是字串,因此這裡同樣利用字串的 split() 方法將 26 個字母拆成陣列的各個元素
18 19 20 | Encrypt.prototype.setCode = function (c) { this .code = c.split( "" , 26); } |
toEncode() 用來編碼,所需要進行的工作就複雜一點,接收參數的字串進行編碼,然後回傳編碼結果的字串。首先建立空字串 result 用來暫存編碼結果, i 為控制變數, len 取得參數 str 的長度
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | Encrypt.prototype.toEncode = function (str) { var result = "" ; var i = 0; var len = str.length; while (i < len) { var regExp = /^[a-z]+$/; if (regExp.test(str[i])) { var j = this .alph.indexOf(str[i]) result += this .code[j]; } else { result += str[i]; } i++; } return result; } |
整個工作用 while 迴圈 (loop) 進行,當控制變數 i 遞增到 len 時結束。這裡測試 str 每個字母是否為英文小寫字母,如果是就找出該字母在 this.alph 的索引值,也就是那個字母在字母表中的序數,然後依該索引值取得密碼表中的字母附接在 result 的最後,相對的,如果不是英文小寫字母,就將該字母直接附接在 result 的最後
28 29 30 31 32 33 34 | if (regExp.test(str[i])) { var j = this .alph.indexOf(str[i]) result += this .code[j]; } else { result += str[i]; } |
toDecode() 的工作幾乎與 toEncode() 一模一樣,除了將 this.alph 與 this.code 的位置對調之外
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | Encrypt.prototype.toDecode = function (str) { var result = "" ; var i = 0; var len = str.length; while (i < len) { var regExp = /^[a-z]+$/; if (regExp.test(str[i])) { var j = this .code.indexOf(str[i]); result += this .alph[j]; } else { result += str[i]; } i++; } return result; } |
我們利用 encryptdemo.html 載入 encrypt.js 測試 Encrypt 物件 (object) ,瀏覽器開啟如下

結果還不錯,編碼、解碼都正確無誤。接下來,我們回到 Encode Software 網頁,來建置 Encode Software 的控制函數與整合 Encrypt 物件功能囉!
中英文術語對照 | |
---|---|
屬性 | attribute |
方法 | method |
字串 | string |
陣列 | array |
參數 | parameter |
迴圈 | loop |
物件 | object |
您可以繼續參考
網頁軟體開發
相關目錄
回 JavaScript 入門指南
回 JavaScript 教材
回首頁
參考資料
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects
http://www.w3schools.com/js/js_obj_intro.asp
http://www.tutorialspoint.com/javascript/javascript_objects.htm
沒有留言:
張貼留言