javascript 中關於array的常用方法詳解,javascriptarray

來源:互聯網
上載者:User

javascript 中關於array的常用方法詳解,javascriptarray

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

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.