详解JS中Array对象扩展与String对象扩展

这篇文章主要介绍了详解JS中Array对象扩展与String对象扩展的相关资料,需要的朋友可以参考下

废话不多说了,直接给大家上array对象扩展代码了,具体代码如下所示:

 /** * Created by laixiangran on 2016/01/07. * Array扩展 */ (function() { // 遍历数组 if (typeof Array.prototype.forEach != "function") { Array.prototype.forEach = function (fn, context) { for (var i = 0; i = 0; i--) { if (i in this && this[i] === item) { return i; } } return -1; }; } // 让数组元素依次调用给定函数,最后返回一个值(从左到右) if (typeof Array.prototype.reduce != "function") { Array.prototype.reduce = function (callback, initialValue) { var previous = initialValue, k = 0, length = this.length; if (typeof initialValue === "undefined") { previous = this[0]; k = 1; } if (typeof callback === "function") { for (k; k  -1; k-=1) { this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this)); } } return previous; }; } // 去掉重复项(唯一性),返回新数组 if (typeof Array.prototype.uniq != "function") { Array.prototype.uniq = function() { var arr = []; arr[0] = this[0]; for (var i = 1; i = 0; i--) { if (item === this[i]) { this.splice(i, 1); } } return this; }; } // 打乱数组顺序 if (typeof Array.prototype.shuffle != "function") { Array.prototype.shuffle = function() { var i = this.length; while (i) { var j = Math.floor(Math.random()*i); var t = this[--i]; this[i] = this[j]; this[j] = t; } return this; }; } // 求数组的最大值 if (typeof Array.prototype.max != "function") { Array.prototype.max = function() { return Math.max.apply({}, this) }; } // 求数组的最小值 if (typeof Array.prototype.max != "function") { Array.prototype.min = function() { return Math.min.apply({}, this) }; } // 判断是否为数组 if (typeof Array.prototype.isArray != "function") { Array.prototype.isArray = function() { return Object.prototype.toString.apply(this) === "[object Array]"; }; } }());

下面是string对象扩展代码如下所示:

 /** * Created by laixiangran on 2015/12/12. * String扩展 */ (function() { // 十六进制颜色值的正则表达式 var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; // RGB颜色转换为16进制 if (typeof String.prototype.rgbToHex != "function") { String.prototype.rgbToHex = function() { var that = this; if (/^(rgb|RGB)/.test(that)) { var aColor = that.replace(/(?:\(|\)|rgb|RGB)*/g,"").split(","); var strHex = "#"; for (var i=0; i

以上就是详解JS中Array对象扩展与String对象扩展的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » JavaScript 教程