基于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); });*/