DIV CSS 佈局教程網

JavaScript 作用域問題實例分析
編輯:關於JavaScript     

最近在專案中需要依 JSON 資料產生樹狀目錄,最初寫出的程式碼如下:

 var folderList = [
 { "FolderName": "ASD", "ChildList": null },
 { "FolderName": "內網公告", "ChildList": null },
 { "FolderName": "測試文檔", "ChildList": null },
 { "FolderName": "軟件開發", "ChildList": null },
 { "FolderName": "Test", "ChildList": [
 { "FolderName": "Test2", "ChildList": [
 { "FolderName": "Test3", "ChildList": null }
 ] }
 ] },
 { "FolderName": "個人", "ChildList": null }
 ];
 var str = '';
 function generateFolders(arr) {
 if (arr.length > 0) {
 str += '<div class="sui-list">';
 for (var i = 0, len = arr.length; i < len; i++) {
 str += '<ul><li>' + arr[i].FolderName + '</li></ul>';
 if (isDefine(arr[i].ChildList)) {
 str += generateFolders(arr[i].ChildList);
 }
 }
 str += '</div>';
 return str;
 } else {
 return '';
 }
 }
 function isDefine(value) {
 if (value == null || value == "" || value == "undefined" || value == undefined || value == "null" || typeof (value) == 'undefined') {
 return false;
 } else {
 value = value + "";
 value = value.replace(/\s/g, "");
 if (value == "") { return false; }
 return true;
 }
 }

結果產生的樹狀結構不如預期:

經排查,發現問題出在 str 定義的位置不對。由於 str 被定義為全域變數,在遞迴呼叫時會不斷累加、互相干擾,導致結果錯亂。只要把 str 改定義為函式內的局部變數即可:

 function generateFolders(arr) {
 var str = '';
 if (arr.length > 0) {
 str += '<div class="sui-list">';
 for (var i = 0, len = arr.length; i < len; i++) {
 str += '<ul><li>' + arr[i].FolderName + '</li></ul>';
 if (isDefine(arr[i].ChildList)) {
 str += generateFolders(arr[i].ChildList);
 }
 }
 str += '</div>';
 return str;
 } else {
 return '';
 }
 }

修改之後就能正確產生前後一致的樹狀結構了:

這個案例提醒我們:遞迴函式中若使用全域變數來累積結果,很容易因為作用域問題而出錯,改用局部變數才是穩妥的做法。以上就是本文的完整內容,希望對大家有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved