Js 数组的各种方法及操作

一、数组去重

  var arr = [0,1,20,3,0,45,6,0];
  Array.prototype.unrepeat = function(){
    var array = [];
    for(var i = 0;i<this.length;i++){
      if(array.indexOf(this[i]) === -1){
        array.push(this[i]);
      }
    }
    return array;
  }
console.log(arr.unrepeat());

二、数组排序

  var arr = [1,5,9,4,8,7]
  arr = arr.sort(function(a,b){return a-b})        // 升序  
  console.log(arr);

三、数组对象的排序

  var arr = [{id:1},{id:7},{id:5},{id:9},{id:20},{id:3}]
  arr = arr.sort(function(a,b){return a.id - b.id})
  console.log(arr)

四、字符串转换数组的小方法

  1)eval():  

    var arr = "[1,2,3,4,5]";
    console.log(eval(arr))      //  性能较差

  2)JSON.parse();

    var arr = "[1,2,3,4,5]";
    console.log(JSON.parse(arr))

  3)es6的Array.of()

    console.log(Array.of(1,2,3,4,8))
    console.log(Array.of("a","b","c","d"))

  4)非字符串数组格式的字符串转化成数组

    var arr = "1,2,3,4,5";
    arr = "["+arr+"]"
    console.log(JSON.parse(arr),eval(arr));

五、数组转化成字符串

  1)toString()

    var arr = ["Creek","Sinoshy","Stream"]

    console.log(arr.toString())   // 以“,”作为分隔符

  2)join()

    var arr = ["Creek","Sinoshy","Stream"]

    console.log(arr.join())   // 默认以逗号分隔,如果给参数,那么会根据给的参数进行分隔

六、删除两个数组中相同的元素

  let arr1 = [1,5,7];
  let arr2 = [1,2,3,4,5,6,7]
  for(let i = 0;i < arr1.length;i ++){
    for(let x = 0;x < arr2.length;x ++){
      if(arr1[i] === arr2[x]){
        arr2.splice(x,1)
      }
    }
  }
  console.log(arr2)

posted on 2018-06-20 16:26  ywx354980  阅读(143)  评论(0编辑  收藏  举报