0

0

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

php中文网

php中文网

发布时间:2016-06-01 09:54:44

|

1298人浏览过

|

来源于php中文网

原创

直接给大家上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对象扩展代码如下所示:

PHP Apache和MySQL 网页开发初步
PHP Apache和MySQL 网页开发初步

本书全面介绍PHP脚本语言和MySOL数据库这两种目前最流行的开源软件,主要包括PHP和MySQL基本概念、PHP扩展与应用库、日期和时间功能、PHP数据对象扩展、PHP的mysqli扩展、MySQL 5的存储例程、解发器和视图等。本书帮助读者学习PHP编程语言和MySQL数据库服务器的最佳实践,了解如何创建数据库驱动的动态Web应用程序。

下载
/**
* 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, "");
        };
    }
} ());

 

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
java入门学习合集
java入门学习合集

本专题整合了java入门学习指南、初学者项目实战、入门到精通等等内容,阅读专题下面的文章了解更多详细学习方法。

2

2026.01.29

java配置环境变量教程合集
java配置环境变量教程合集

本专题整合了java配置环境变量设置、步骤、安装jdk、避免冲突等等相关内容,阅读专题下面的文章了解更多详细操作。

2

2026.01.29

java成品学习网站推荐大全
java成品学习网站推荐大全

本专题整合了java成品网站、在线成品网站源码、源码入口等等相关内容,阅读专题下面的文章了解更多详细推荐内容。

0

2026.01.29

Java字符串处理使用教程合集
Java字符串处理使用教程合集

本专题整合了Java字符串截取、处理、使用、实战等等教程内容,阅读专题下面的文章了解详细操作教程。

0

2026.01.29

Java空对象相关教程合集
Java空对象相关教程合集

本专题整合了Java空对象相关教程,阅读专题下面的文章了解更多详细内容。

3

2026.01.29

clawdbot ai使用教程 保姆级clawdbot部署安装手册
clawdbot ai使用教程 保姆级clawdbot部署安装手册

Clawdbot是一个“有灵魂”的AI助手,可以帮用户清空收件箱、发送电子邮件、管理日历、办理航班值机等等,并且可以接入用户常用的任何聊天APP,所有的操作均可通过WhatsApp、Telegram等平台完成,用户只需通过对话,就能操控设备自动执行各类任务。

25

2026.01.29

clawdbot龙虾机器人官网入口 clawdbot ai官方网站地址
clawdbot龙虾机器人官网入口 clawdbot ai官方网站地址

clawdbot龙虾机器人官网入口:https://clawd.bot/,clawdbot ai是一个“有灵魂”的AI助手,可以帮用户清空收件箱、发送电子邮件、管理日历、办理航班值机等等,并且可以接入用户常用的任何聊天APP,所有的操作均可通过WhatsApp、Telegram等平台完成,用户只需通过对话,就能操控设备自动执行各类任务。

16

2026.01.29

Golang 网络安全与加密实战
Golang 网络安全与加密实战

本专题系统讲解 Golang 在网络安全与加密技术中的应用,包括对称加密与非对称加密(AES、RSA)、哈希与数字签名、JWT身份认证、SSL/TLS 安全通信、常见网络攻击防范(如SQL注入、XSS、CSRF)及其防护措施。通过实战案例,帮助学习者掌握 如何使用 Go 语言保障网络通信的安全性,保护用户数据与隐私。

8

2026.01.29

俄罗斯Yandex引擎入口
俄罗斯Yandex引擎入口

2026年俄罗斯Yandex搜索引擎最新入口汇总,涵盖免登录、多语言支持、无广告视频播放及本地化服务等核心功能。阅读专题下面的文章了解更多详细内容。

622

2026.01.28

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
WEB前端教程【HTML5+CSS3+JS】
WEB前端教程【HTML5+CSS3+JS】

共101课时 | 8.6万人学习

JS进阶与BootStrap学习
JS进阶与BootStrap学习

共39课时 | 3.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号