JavaScript Array 를 모 의 한 List

더 읽 기
 
JavaScript 의 Array 대상 을 모 의 합 니 다.
주로 pust, pop. shift, foreach, concat, slice 등 방법 을 실현 하여 추 후 업데이트 합 니 다.
 
 
'use strict'

function List() {
	this.length = 0;
	if (arguments.length === 1) {
		if (typeof(arguments[0]) === 'string') {
			this[0] = arguments[0];
			this.length++;
		} else if (typeof(arguments[0]) === 'number') {
			this.length = arguments[0];
		}
	} else {
		for (var i = 0, len = arguments.length; i < len; i++) {
			this[i] = arguments[i];
			this.length++;
		}
	}

}

/**
 * [push description]
 * @return {[type]} [description]
 */
List.prototype.push = function() {
	this.length++;
	this[this.length - 1] = arguments[0];
	return this;
}

/**
 * [slice description]
 * @return {[type]} [description]
 */
List.prototype.slice = function() {
	var list = new List();
	var start = arguments[0] || 0;
	var end = arguments[1] || this.length;
	for (var i = start; i < end; i++) {
		list.push(this[i]);
	}
	return list;
}

/**
 * [shift description]
 * @return {[type]} [description]
 */
List.prototype.shift = function() {
	var first = this[0];
	delete this[0];
	this.length--;
	for (var key in this) {
		if (!isNaN(key)) {
			var v = this[key];
			delete this[key];
			var k = (parseInt(key, 10)) - 1;
			this[k] = v;
		}
	}
	return first;
}

/**
 * [pop description]
 * @return {[type]} [description]
 */
List.prototype.pop = function() {
	var last = this[this.length - 1];
	delete this[this.length - 1];
	this.length--;
	return last;
}

/**
 * [concat description]
 * @return {[type]} [description]
 */
List.prototype.concat = function() {
	var target = arguments[0];
	var _this = this;
	var length = _this.length;
	if (target instanceof List) {
		for (var key in target) {
			if (!isNaN(key)) {
				_this[_this.length] = target[key];
				_this.length++;
			}
		}
	}
}

/**
 * [reverse description]
 * @return {[type]} [description]
 */
List.prototype.reverse = function() {
	var list = new List();
	for (var i = this.length - 1; i > -1; i--) {
		list.push.call(list, this[i]);
	}
	return list;
}

/**
 * [join description]
 * @return {[type]} [description]
 */
List.prototype.join = function() {
	var tag = (arguments.length > 0 ? arguments[0] : ',');
	var str = '';
	for (var i = 0, len = this.length; i < len; i++) {
		str += this[i] + tag;
	}
	str = str.substring(0, str.length - 1);
	return str.toString();
}


/**
 * [forEach description]
 * @param  {Function} fn [description]
 * @return {[type]}      [description]
 */
List.prototype.forEach = function(fn) {
	for (var i = 0, len = this.length; i < len; i++) {
		fn(this[i]);
	}
}

/**
 * [toString description]
 * @return {[type]} [description]
 */
List.prototype.toString = function() {
	return this.join();
}


좋은 웹페이지 즐겨찾기