模拟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(); }
相关推荐
nmgxzm00 2020-11-10
ifconfig 2020-10-14
hhanbj 2020-11-17
zfszhangyuan 2020-11-16
古叶峰 2020-11-16
一个智障 2020-11-15
jipengx 2020-11-12
81427005 2020-11-11
xixixi 2020-11-11
游走的豚鼠君 2020-11-10
苗疆三刀的随手记 2020-11-10
Web卓不凡 2020-11-03
小飞侠V 2020-11-02
帕尼尼 2020-10-30
爱读书的旅行者 2020-10-26
帕尼尼 2020-10-23
杏仁技术站 2020-10-23
淼寒儿 2020-10-22