模拟JavaScript Array实现的List
程序员文章站
2022-07-06 11:34:42
...
模拟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(); }
上一篇: 小米真无线降噪耳机有没有主动降噪?
推荐阅读