国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

javascript 中關于array的常用方法詳解

2019-11-19 16:39:53
字體:
來源:轉載
供稿:網友

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;  })}

第四部分

根據指定條件對數組進行操作。

/** * 根據指定條件(如回調或對象的某個屬性)進行分組,構成對象返回。 * @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));}/** * ES6的并集 * @param target * @param array * @returns {Array} */function union1(target,array) {  return Array.from(new Set([...target,...array]));}/** * 對兩個數組取交集 * @param target * @param array * @returns {Array.<T>|*} */function intersect(target,array) {  return target.filter(function(n) {    return ~array.indexOf(n);  })}/** * ES6 交集 * @param target * @param array * @returns {Array} */function intersect1(target,array) {  array = new Set(array);  return Array.from(new Set([...target].filter(value => array.has(value))));}/** * 差集 * @param target * @param array * @returns {ArrayBuffer|Blob|Array.<T>|string} */function diff(target,array) {  var result = target.slice();  for (var i = 0;i < result.length;i++) {    for (var j = 0; j < array.length;j++) {      if (result[i] === array[j]) {        result.splice(i,1);        i--;        break;      }    }  }  return result;}/** * ES6 差集 * @param target * @param array * @returns {Array} */function diff1(target,array) {  array = new Set(array);  return Array.from(new Set([...target].filter(value => !array.has(value))));}

第六部分

數組包含指定目標。

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

 最后模擬一下數組中的pop,oush,shift和unshift的實現原理

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;};

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 红原县| 古田县| 信丰县| 前郭尔| 义马市| 昌平区| 江西省| 上蔡县| 永丰县| 宜城市| 汉中市| 阜新市| 信宜市| 贵德县| 金昌市| 巴彦县| 周口市| 陇西县| 旬阳县| 图木舒克市| 阳高县| 新和县| 扶绥县| 富锦市| 裕民县| 湘阴县| 托克托县| 城步| 遂宁市| 台东县| 育儿| 三原县| 武定县| 广水市| 礼泉县| 太康县| 延边| 香港 | 台南市| 晴隆县| 建湖县|