详解JS中Array对象扩展与String对象扩展_javascript技巧
程序员文章站
2022-03-16 16:54:52
...
废话不多说了,直接给大家上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
上一篇: jsp是什么
推荐阅读
-
详解JavaScript中js对象与JSON格式字符串的相互转换
-
扩展JS Date对象时间格式化功能的小例子_javascript技巧
-
以JSON形式将JS中Array对象数组传至后台的方法_javascript技巧
-
以JSON形式将JS中Array对象数组传至后台的方法_javascript技巧
-
JS中的prototype与面向对象的实例讲解_javascript技巧
-
Javascript String对象扩展HTML编码和解码的方法_javascript技巧
-
JS中的prototype与面向对象的实例讲解_javascript技巧
-
JS动态添加与删除select中的Option对象(示例代码)_javascript技巧
-
Javascript String对象扩展HTML编码和解码的方法_javascript技巧
-
javascript Array数组对象的扩展函数代码_javascript技巧