javascript 中关于array的常用方法
最近总结了一些关于array中的常用方法,
其中大部分的方法来自于《JavaScript框架设计》这本书,
如果有更好的方法,或者有关于string的别的常用的方法,希望大家不吝赐教。
第一部分
数组去重,总结了一些数组去重的方法,代码如下:
/** * 去重操作,有序状态 * @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);}/** * ES6写法,有序状态 * @param target * @returns {Array} */function unique2(target) { return Array.from(new Set(target));}function unique3(target) { return [...new Set(target)];}
第二部分
数组中获取值,包括最大值,最小值,随机值。
/** * 返回数组中的最小值,用于数字数组 * @param target * @returns {*} */function min(target) { return Math.min.apply(0,target);}/** * 返回数组中的最大值,用于数字数组 * @param target * @returns {*} */function max(target) { return Math.max.apply(0,target);}/** * 从数组中随机抽选一个元素出来 * @param target * @returns {*} */function random(target) { return target[Math.floor(Math.random() * target.length)];}
第三部分
对数组本身的操作,包括移除值,重新洗牌,扁平化和过滤不存在的值
/** * 移除数组中指定位置的元素,返回布尔表示成功与否 * @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 {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;}/** * 过滤属性中的null和undefined,但不影响原数组 * @param target * @returns {Array.<T>|*} */function compat(target) { return target.filter(function(el) { return el != null; })}
新闻热点
疑难解答
图片精选