js循环多维数组

var arr = [ 1, 2, 1, [ 5, 6, [ 8, 9 ] ] ];
Array.prototype.each = function(fn) {
	try {
		this.i || (this.i = 0);
		if (this.length > 0 && fn.constructor === Function) {
			while (this.i < this.length) {
				var e = this[this.i];
				if (e && e.constructor == Array) {
					e.each(fn);
				} else {
					fn.call(e, e);
				}
				this.i++;
			}
			this.i == null;
		}
	} catch (ex) {

	}
	return this;
}

arr.each(function(item) {
	console.log(item);
});

转至尚学堂js视频教程

点赞

发表评论