查看: 2522|回复: 2

[原创发布] 非常好的数组操作库整理

[复制链接]
梦石
0
星屑
7735
在线时间
1227 小时
注册时间
2008-12-14
回帖
504
发表于 2018-3-3 17:52:37 | 显示全部楼层 |阅读模式

加入我们,或者,欢迎回来。

您需要 登录 才可以下载或查看,没有账号?注册会员

×
// 贴这里备忘,分享吧。
// 用法:可以打开任意一个插件,将代码考进去,也可以做成插件,导入插件。然后比如说我要删除一个数组中的元素就[1,2,3].remove(2);就可以了。这个是删完自动改变数组大小的。。。
// 看不懂我再注释。。。
//===========================================================================
// Array
//===========================================================================
Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};

Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

Array.prototype.realLength = function() {
    var amount = 0;
    for(var i = 0; i < this.length; i++) {
        var item = this[i];
        if (item && !Number.isNaN(item)) {
            amount++;
        }
    }
    return amount;
};

Array.prototype.isEmpty = function() {
    return this.length === 0;
};

Array.prototype.needCompact = function() {
    return this.contains(null);
};

Array.prototype.compact = function() {
    if (!this.needCompact()) {
        return this;
    }
    for(var i = 0; i < this.length; i++) {
        if (!this[i]) {
            this.splice(i, 1);
            return this.compact();
        }
    }   
    return this;
};

Array.prototype.insert = function(index, item) {
    this.splice(index, 0, item);
};

Array.prototype.count = function(item) {
    var amount = 0;
    for(var i = 0; i < this.length; i++) {
        if (this[i] === item) {
            amount++;
        }
    }
    return amount;
};

评分

参与人数 1赞 +1 收起 理由
白嫩白嫩的 + 1 塞糖

查看全部评分

需要购买本人MV插件必须先加wx好友。加不上wx就是本人忙,没时间卖。原则上太久以前的插件也不想卖,因为我也忘了,维护上会不给力。wx名:alskyif    本人插件地址:
   LCK_SRPG梦幻模拟战、火焰纹章类系统
   究极立绘ADV系统

   究极换装统合系统
   究极! 回想与CG系统
   消息文字的距离调整  
   自动返回上一张地图
梦石
0
星屑
7427
在线时间
948 小时
注册时间
2017-9-27
回帖
566
发表于 2018-3-3 18:40:11 | 显示全部楼层
原生的js数组操作里面没有移除元素的方法吗?
回复

使用道具 举报

梦石
0
星屑
4716
在线时间
501 小时
注册时间
2013-12-7
回帖
333

极短28参与极短27参与

发表于 2018-3-8 12:40:11 | 显示全部楼层
本帖最后由 ekmomo 于 2018-3-8 13:32 编辑

我也写俩吧
//去重
Array.prototype.unique =function(){return [...new Set(this)];}
//按值删
Array.prototype.remove = function() {
        if (this + ""){
                var arg = [...arguments];
                while(arg.length){
                        var val = arg.pop();
                        this.forEach(function(item, index){
                                if (item === val) this.splice(index, 1);
                        }, this);
                }
        }
        return this;
};

评分

参与人数 1赞 +1 收起 理由
白嫩白嫩的 + 1 塞糖

查看全部评分

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册会员

本版积分规则

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部