基於ECMAScript5提供遍歷數組的forEach方法僅能遍歷一維數組,沒有提供循環遍歷多維數組的方法,所以實現如下遍歷多維數組的each方法,以此遍歷多維數組。
注意:此處新增了遍歷空數組與對象的顯示方式
//遍歷多維數組方法實現 Array.prototype.each = function (fn) { try { //定義計數器 const ZERO = 0; this.i = ZERO; //判斷數組非空且參數的構造器為函數 if (this.length > this.i && fn.constructor === Function) { while (this.length > this.i) { var item = this[this.i]; //如果當前元素是數組 if (item && item.constructor === Array) { if (item.length > ZERO) { item.each(fn); } else { //空數組顯示"[]", 而非空白 fn.call(item, "[]"); } } else {//當前元素非數組,此處擴展遍歷對象,以鍵值對方式顯示,而非[object Object] if (item && typeof item === "object") { //非空對象 if (Object.keys(item).length > ZERO) { for (const key in item) { fn.call(item, key + " : " + item[key]); } } else { //空對象 fn.call(item, "{}"); } } else {//其余元素,包括對象類型的null fn.call(item, item); } } this.i++; } //銷毀計數器,回收內存 delete this.i; } } catch (e) { console.log("error happened in printing multiple-dimension array. error message : " + e); throw e; } return this; }; var array = ["中國", "Charles", 0, ["A", "B", "C"], ["D", ["E", "F"], "G"], { name: "ITACHI", gander: "Male" }, [], null, undefined, false]; //遍歷多維數組 array.each(function (item) { alert(item); }); //遍歷一維數組 /*array.forEach(function (item, index, arr) { alert(item); });*/