6 Dec 2017

数组常用方法

  1. 遍历:
    var row = ['zhangsan','lisi','wangwu','xiaoqiang']; 
     for (var i in row){
      console.log(i + ':' + row[i]);
     }
    
  2. 数组连接(新数组):["a","b"].concact("d","e");
  3. 数组转换为字符串:["a","b"].join(separator);["a","b","c"].toString()
  4. 字符串转换为数组:'a,b,c'.split(',');
  5. 原数组去掉并返回最后一个元素:["a","b"].pop()
  6. 原数组去掉并返回第一一个元素:["a","b"].shift()
  7. 插入到数组的开头:[1,2].unshift("a","b")
  8. 参数添加到数组的结尾:[1,2].push("a","b")
  9. 数组中的元素反转:[1,2].reverse()
  10. 截取数组(新数组):["a","b"].slice(start,end)
  11. 数组排序:["a","b"].sort();[3,4,2,7].sort(function(e1,e2){return e1-e2;})
  12. 数组元素的删除 取代和插入:["a","b"].splice(start,delCount[,item1,item2[,...]]])
  13. 查找数组包含的字符串 : Array.prototype.arrayFindString=function(arr,string) {return arr.join("").indexOf(string);}
  14. 删除数组中指定元素: Array.prototype.remove = function(dx) {if(isNaN(dx)||dx>this.length){return false;}this.splice(dx,1);}
  15. 数组的拷贝:["a","b"].slice(0);arrayObj.concat();
  16. 过滤掉小于 10 的数组元素(新数组):[12, 5, 8].filter(function(el, index, array) {return (el>= 10);});
  17. 数组转为大写(新数组):["hello", "Array", "WORLD"].map(function(v){ return v.toUpperCase();});
  18. 是否有数组元素大于等于10:[12, 5, 8].some(function(el, index, array) {return (element >= 10);});
  19. 是否所有元素都大于等于10:[12, 5, 8].every(function(element, index, array) {return (element >= 10);});
  20. 打印数组内容:[2, 5, 9].forEach(function (el, index, array) { console.log("[" + index + "] is " + el);});
  21. 查找符合条件的元素:[2, 5, 9].indexOf(2);array.lastIndexOf(2);
  22. Array对象去除重复项
    //ES5:
    Array.prototype.uniq = function () {
     var arr = [];
     var flag = true;
     this.forEach(function(item) {
     // 排除 NaN (重要!!!)
     if (item != item) {
     flag && arr.indexOf(item) === -1 ? arr.push(item) : '';
     flag = false;
     } else {
     arr.indexOf(item) === -1 ? arr.push(item) : ''
     }
     });
     return arr;
    }
    //ES6的实现
    Array.prototype.uniq = function() {
     //return Array.from(new Set(this));
     return [...new Set(this)];
    }
    
  23. 交集、并集、差集
    let a=new Set([1,2,3]);
    let b=new Set([4,3,2]);
    //交集
    let union= [...new Set([...a,...b])];
    console.log(union);
    //并集
    let intersect= [...new Set([...a].filter(x=> b.has(x)))];
    console.log(intersect);
    //差集
    let difference= [...new Set([...a].filter(x=> !b.has(x)))];
    console.log(difference);
    

Tags: