首页 > web前端 > js教程 > 正文

javascript中关于array的常用方法

迷茫
发布: 2017-03-26 14:55:54
原创
1233人浏览过

最近总结了一些关于array中的常用方法,

其中大部分的方法来自于《JavaScript框架设计》这本书,

如果有更好的方法,或者有关于string的别的常用的方法,希望大家不吝赐教。

直接上代码:

/**
 * 判定数组是否包含指定目标
 * @param target
 * @param item
 * @returns {boolean}
 */
function contains(target,item) {
    return target.indexOf(item) > -1;
}

/**
 * 移除数组中指定位置的元素,返回布尔表示成功与否
 * @param target
 * @param index
 * @returns {boolean}
 */
function removeAt(target,index) {
    return !!target.splice(index,1).length;
}

/**
 * 移除数组中第一个匹配传参的那个元素,返回布尔表示成功与否
 * @param target
 * @param item
 * @returns {boolean}
 */
function remove(target,item) {
    const index = target.indexOf(item);
    if (~index) {
        return removeAt(target,index);
    }
    return false;
}

/**
 * 对数组进行洗牌
 * @param array
 * @returns {array}
 */
function shuffle(array) {
    let m = array.length, t, i;
    // While there remain elements to shuffle…
    while (m) {
        // Pick a remaining element…
        i = Math.floor(Math.random() * m--);

        // And swap it with the current element.
        t = array[m];
        array[m] = array[i];
        array[i] = t;
    }
    return array;
}

/**
 * 从数组中随机抽选一个元素出来
 * @param target
 * @returns {*}
 */
function random(target) {
    return target[Math.floor(Math.random() * target.length)];
}

/**
 * 对数组进行平坦化处理,返回一个一维的新数组
 * @param target
 * @returns {Array}
 */
function flatten (target) {
    let result = [];
    target.forEach(function(item) {
        if(Array.isArray(item)) {
            result = result.concat(flatten(item));
        } else {
            result.push(item);
        }
    });
    return result;
}

/**
 * 去重操作,有序状态
 * @param target
 * @returns {Array}
 */
function unique(target) {
    let result = [];
    loop: for (let i = 0,n = target.length;i < n; i++) {
        for (let x = i + 1;x < n;x++) {
            if (target[x] === target[i]) {
                continue loop;
            }
        }
        result.push(target[i]);
    }
    return result;
}

/**
 * 去重操作,无序状态,效率最高
 * @param target
 * @returns {Array}
 */
function unique1(target) {
    let obj = {};
    for (let i = 0,n = target.length; i < n;i++) {
        obj[target[i]] = true;
    }
    return Object.keys(obj);
}

/**
 * 过滤属性中的null和undefined,但不影响原数组
 * @param target
 * @returns {Array.<T>|*}
 */
function compat(target) {
    return target.filter(function(el) {
        return el != null;
    })
}

/**
 * 根据指定条件(如回调或对象的某个属性)进行分组,构成对象返回。
 * @param target
 * @param val
 * @returns {{}}
 */
function groupBy(target,val) {
    var result = {};
    var iterator = isFunction(val) ? val : function(obj) {
        return obj[val];
    };
    target.forEach(function(value,index) {
        var key = iterator(value,index);
        (result[key] || (result[key] = [])).push(value);
    });
    return result;
}
function isFunction(obj){
    return Object.prototype.toString.call(obj) === '[object Function]';
}

// 例子
function iterator(value) {
   if (value > 10) {
       return 'a';
   } else if (value > 5) {
       return 'b';
   }
   return 'c';
}
var target = [6,2,3,4,5,65,7,6,8,7,65,4,34,7,8];
console.log(groupBy(target,iterator));



/**
 * 获取对象数组的每个元素的指定属性,组成数组返回
 * @param target
 * @param name
 * @returns {Array}
 */
function pluck(target,name) {
    let result = [],prop;
    target.forEach(function(item) {
        prop = item[name];
        if (prop != null) {
            result.push(prop);
        }
    });
    return result;
}

/**
 * 根据指定条件进行排序,通常用于对象数组
 * @param target
 * @param fn
 * @param scope
 * @returns {Array}
 */
function sortBy(target,fn,scope) {
    let array = target.map(function(item,index) {
        return {
            el: item,
            re: fn.call(scope,item,index)
        };
    }).sort(function(left,right) {
        let a = left.re, b = right.re;
        return a < b ? -1 : a > b ? 1 : 0;
    });
    return pluck(array,'el');
}

/**
 * 对两个数组取并集
 * @param target
 * @param array
 * @returns {Array}
 */
function union(target,array) {
    return unique(target.concat(array));
}

/**
 * 对两个数组取交集
 * @param target
 * @param array
 * @returns {Array.<T>|*}
 */
function intersect(target,array) {
    return target.filter(function(n) {
        return ~array.indexOf(n);
    })
}

/**
 * 返回数组中的最小值,用于数字数组
 * @param target
 * @returns {*}
 */
function min(target) {
    return Math.min.apply(0,target);
}

/**
 * 返回数组中的最大值,用于数字数组
 * @param target
 * @returns {*}
 */
function max(target) {
    return Math.max.apply(0,target);
}
登录后复制

最后模拟一下数组中的pop,oush,shift和unshift的实现原理

立即学习Java免费学习笔记(深入)”;

const _slice = Array.prototype.slice;
Array.prototype.pop = function() {
    return this.splice(this.length - 1,1)[0];
};
Array.prototype.push = function() {
    this.splice.apply(this,[this.length,0].concat(_slice.call(arguments)));
    return this.length;
};
Array.prototype.shift = function() {
    return this.splice(0,1)[0];
};
Array.prototype.unshift = function() {
    this.splice.apply(this,
        [0,0].concat(_slice.call(arguments)));
    return this.length;
};
登录后复制

以上就是javascript中关于array的常用方法的详细内容,更多请关注php中文网其它相关文章!

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

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