基于ECMAScript5提供遍历数组的forEach方法仅能遍历一维数组,没有提供循环遍历多维数组的方法,所以根据白鹤翔老师的讲解,实现如下遍历多维数组的each方法,以此遍历多维数组。
<script type="text/javascript" charset="UTF-8">
//遍历多维数组方法实现
Array.prototype.each = function (fn) {
try {
this.i = 0;
if (this.length > this.i && fn.constructor == Function) {
while (this.length > this.i) {
var elem = this[this.i];
if (elem.constructor == Array) {
elem.each(fn);
} else {
fn.call(elem, elem);
}
this.i++;
}
}
} catch (e) {
console.log("error happened in printing multipul-dimention array. error message : " + e);
throw e;
}
return this;
};
var array = ["中国", "Charles", 7526, ["A", "B", "C"], ["D", ["E", "F"], "G"], {
"gander": "Male"
}];
//遍历多维数组
array.each(function (item) {
alert(item);
});
//遍历一维数组
array.forEach(function (item, index, arr) {
alert(item);
});
</script>