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


Posted in Javascript onJanuary 07, 2016

废话不多说了,直接给大家上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 < this.length; i++) {
if (typeof fn === "function" && Object.prototype.hasOwnProperty.call(this, i)) {
fn.call(context, this[i], i, this);
}
}
};
}
// 让数组中的每一个元素调用给定的函数,然后把得到的结果放到新数组中返回
if (typeof Array.prototype.map != "function") {
Array.prototype.map = function (fn, context) {
var arr = [];
if (typeof fn === "function") {
for (var k = 0, length = this.length; k < length; k++) {
arr.push(fn.call(context, this[k], k, this));
}
}
return arr;
};
}
// 把符合条件的元素放到一个新数组中返回
if (typeof Array.prototype.filter != "function") {
Array.prototype.filter = function (fn, context) {
var arr = [];
if (typeof fn === "function") {
for (var k = 0, length = this.length; k < length; k++) {
fn.call(context, this[k], k, this) && arr.push(this[k]);
}
}
return arr;
};
}
// 如果数组中的每个元素都能通过给定的函数的测试,则返回true,反之false
if (typeof Array.prototype.every != "function") {
Array.prototype.every = function (fn, context) {
var passed = true;
if (typeof fn === "function") {
for (var k = 0, length = this.length; k < length; k++) {
if (passed === false) break;
passed = !!fn.call(context, this[k], k, this);
}
}
return passed;
};
}
// 类似every函数,但只要有一个通过给定函数的测试就返回true
if (typeof Array.prototype.some != "function") {
Array.prototype.some = function (fn, context) {
var passed = false;
if (typeof fn === "function") {
for (var k = 0, length = this.length; k < length; k++) {
if (passed === true) break;
passed = !!fn.call(context, this[k], k, this);
}
}
return passed;
};
}
// 返回元素在数组的索引,没有则返回-1,从左到右
if (typeof Array.prototype.indexOf != "function") {
Array.prototype.indexOf = function (item, index) {
var n = this.length,
i = index == null ? 0 : index < 0 ? Math.max(0, n + index) : index;
for (; i < n; i++) {
if (i in this && this[i] === item) {
return i
}
}
return -1
};
}
// 返回元素在数组的索引,没有则返回-1,从右到左
if (typeof Array.prototype.lastIndexOf != "function") {
Array.prototype.lastIndexOf = function (item, index) {
var n = this.length,
i = index == null ? n-1 : index < 0 ? Math.max(0, n + index) : index;
for (; 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 < length; k++) {
this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this));
}
}
return previous;
};
}
// 让数组元素依次调用给定函数,最后返回一个值(从右到左)
if (typeof Array.prototype.reduceRight != "function") {
Array.prototype.reduceRight = function (callback, initialValue) {
var length = this.length, k = length - 1, previous = initialValue;
if (typeof initialValue === "undefined") {
previous = this[length - 1];
k--;
}
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 < this.length; i++) {
if (arr.indexOf(this[i]) == -1) {
arr.push(this[i]);
}
}
return arr;
};
}
// 指定删除数组中某值
if (typeof Array.prototype.remove != "function") {
Array.prototype.remove = function(item) {
for (var i = this.length; 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<aColor.length; i++) {
var hex = Number(aColor[i]).toString(16);
if (hex === "0") {
hex += hex;
}
strHex += hex;
}
if (strHex.length !== 7) {
strHex = that;
}
return strHex;
}else if (reg.test(that)) {
var aNum = that.replace(/#/,"").split("");
if (aNum.length === 6){
return that;
}else if (aNum.length === 3) {
var numHex = "#";
for (var j=0; j<aNum.length; j++) {
numHex += (aNum[j]+aNum[j]);
}
return numHex;
}
}else{
return that;
}
};
}
// 16进制颜色转为RGB格式
if (typeof String.prototype.hexToRgb != "function") {
String.prototype.hexToRgb = function() {
var sColor = this.toLowerCase();
if (sColor && reg.test(sColor)) {
if (sColor.length === 4) {
var sColorNew = "#";
for (var i = 1; i < 4; i++) {
sColorNew += sColor.slice(i,i+1).concat(sColor.slice(i,i+1));
}
sColor = sColorNew;
}
// 处理六位的颜色值
var sColorChange = [];
for (var j=1; j<7; j+=2) {
sColorChange.push(parseInt("0x"+sColor.slice(j,j+2)));
}
return "RGB(" + sColorChange.join(",") + ")";
}else{
return sColor;
}
};
}
// 移除字符串首尾空白
if (typeof String.prototype.trim != "function") {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
}
}());
Javascript 相关文章推荐
兼容Mozilla必须知道的知识。
Jan 09 Javascript
JavaScript加入收藏夹功能(兼容IE、firefox、chrome)
May 05 Javascript
js生成的验证码的实现与技术分析
Sep 17 Javascript
简单讲解AngularJS的Routing路由的定义与使用
Mar 05 Javascript
Javascript获取随机数的实现方法
Jun 22 Javascript
使用PBFunc在Powerbuilder中支付宝当面付款功能
Oct 01 Javascript
Seajs是什么及sea.js 由来,特点以及优势
Oct 13 Javascript
js时间戳转yyyy-MM-dd HH-mm-ss工具类详解
Apr 30 Javascript
EasyUI 数据表格datagrid列自适应内容宽度的实现
Jul 18 Javascript
Vue2.4+新增属性.sync、$attrs、$listeners的具体使用
Mar 08 Javascript
如何用JS模拟实现数组的map方法
Jul 30 Javascript
详解ES6 中的Object.assign()的用法实例代码
Jan 11 Javascript
js创建对象的方法汇总
Jan 07 #Javascript
JavaScript截取、切割字符串的技巧
Jan 07 #Javascript
js确认框confirm()用法实例详解
Jan 07 #Javascript
实例讲解jquery与json的结合
Jan 07 #Javascript
javascript仿百度输入框提示自动下拉补全
Jan 07 #Javascript
基于jquery实现表格无刷新分页
Jan 07 #Javascript
js密码强度检测
Jan 07 #Javascript
You might like
php给每个段落添加空格的方法
2015/03/20 PHP
详细解读php的命名空间(二)
2018/02/21 PHP
[对联广告] JS脚本类
2006/08/27 Javascript
JavaScript 不只是脚本
2007/05/30 Javascript
javascript css styleFloat和cssFloat
2010/03/15 Javascript
Cookie 小记
2010/04/01 Javascript
jquery、js调用iframe父窗口与子窗口元素的方法整理
2014/07/31 Javascript
jQuery实现点击该行即可删除HTML表格行
2014/10/17 Javascript
跟我学习javascript的异步脚本加载
2015/11/20 Javascript
AngularJS 与百度地图的结合实例
2016/10/20 Javascript
扩展Bootstrap Tooltip插件使其可交互的方法
2016/11/07 Javascript
Bootstrap3 图片(响应式图片&amp;图片形状)
2017/01/04 Javascript
详解AngularJS ui-sref的简单使用
2017/04/24 Javascript
JS中的算法与数据结构之列表(List)实例详解
2019/08/16 Javascript
[03:26]回顾2015国际邀请赛中国区预选赛
2015/06/09 DOTA
python学习必备知识汇总
2017/09/08 Python
Python实现的直接插入排序算法示例
2018/04/29 Python
Scrapy框架爬取西刺代理网免费高匿代理的实现代码
2019/02/22 Python
Python常用特殊方法实例总结
2019/03/22 Python
python操作kafka实践的示例代码
2019/06/19 Python
详解python 利用echarts画地图(热力图)(世界地图,省市地图,区县地图)
2019/08/06 Python
澳大利亚牛仔裤商店:Just Jeans
2016/10/13 全球购物
美国的Eastbay旗下的运动款子品牌:Final-Score
2018/01/01 全球购物
意大利领先的奢侈品在线时装零售商:MCLABELS
2020/10/13 全球购物
FragranceNet中文网:北美健康美容线上零售商
2020/08/26 全球购物
什么是符号链接,什么是硬链接?符号链接与硬链接的区别是什么?
2014/01/19 面试题
介绍下static、final、abstract区别
2015/01/30 面试题
高中生自我鉴定范文
2013/10/30 职场文书
汽修专业学生自我鉴定
2013/11/16 职场文书
党支部书记先进事迹
2014/01/17 职场文书
预备党员承诺书
2014/03/25 职场文书
带病坚持工作事迹
2014/05/03 职场文书
酒后驾车标语
2014/06/30 职场文书
投资意向书
2014/07/30 职场文书
毕业生自荐材料范文
2014/12/30 职场文书
电力培训学习心得体会
2016/01/11 职场文书