JS优雅写法记录

1、ES6语法篇

//ES6语法
// spread扩展符(...),

//另:
//1、函数声明:
    var fun1 = tit =>{ console.log(tit) };
    var fun2 = (tit) =>{ console.log(tit) };
    fun1('fun1');
    fun2('fun2');

    //函数柯里化:是将多参函数转换成一系列的单参函数。
    //示例:
    var add1 = (a, b) => console.log(a + b);
    add1(1, 2);  // => 3
    //修改
    var add2 = a => b => console.log(a + b);
    add2(1)(2);  // => 3

    //组合函数:实现方式类似于Array.prototype.reduce 和 RxJS.reduce
    var compose = (fn1, fn2) => (arg) => fn1(fn2(arg));
    var a = arg => arg + 'a';
    var b = arg => arg + 'b';
    //reduce in React中:
    export default function compose(...funcs) {
      if (funcs.length === 0) {
         return arg => arg
      } else {
        const last = funcs[funcs.length - 1]
        const rest = funcs.slice(0, -1)
        return (...args) => rest.reduceRight((composed, f) => f(composed), last(...args))
      }
     }
    
var c = compose(a, b); // 将a,b函数进行组合
c('c');  // => cba

2、js简洁写法

//js转换成bool值的六个false
    !0 = true,              !undefined = true
    !'' = true,             !NaN  = true
    ! null = true ,         !false  = true

    //1.丢弃小数部分,保留整数部分
    parseInt(3.5);  //3
    parseInt(-3.5);  //-3
    //同上
    ~~3.5  //3
    ~~-3.5 //-3
    //同上
    3.5 | 0  //3
    -3.5 | 0  //-3

    //2.向上取整,有小数就加1
    console.log(Math.ceil(3.5));  //4
    console.log(Math.ceil(-3.5));  //-3

    //3.四舍五入
    console.log(Math.round(3.5) ); //4
    console.log(Math.round(-3.5) ); //-3

    //4.向下取整
    console.log(Math.floor(3.5) );  //3
    console.log(Math.floor(-3.5) );  //-4

    //5.正常处理
    console.log(parseFloat('3.5') );  //3.5
    console.log(parseFloat('3.5rf') );  //3.5
    console.log(parseFloat('-3.5') );  //-3.5
    console.log(parseFloat('-3.5rf') );  //-3.5

    //6.if语句写法
    var a = 1;
    var b = 1;

    if(a === 1){
       a = 'a等于1';
    }else if(a === 2){
       a = 'a等于2';
    }else if(a === 3){
       a = 'a等于3';
    }
    可以更改为:(a === 1) && (a = 'a等于1') || (a === 2) && (a = 'a等于2') || (a === 3) && (a = 'a等于3')
    以上写法效果等同

3、js数组篇

//1、数组元素的新增
   var arr = [];
   console.log(arr.push(1));   //数组直接push,返回的是数组长度
   arr.push(1);
   console.log(arr);   //push之后,数组已经变成:[1]

//2、数组元素的删除
   方式一:
   var arr1 = [1 , 2];
   console.log(arr1.splice(1, 1));    //直接删除,返回的是删除掉的元素
   arr1.splice(1, 1);  //先删除再打印,是删除后剩余的结果splice(index, len)分别为起始下标和要删除的长度
   console.log(arr1);
   方式二:
   console.log(['1','2','3','4'].filter((item,index,self) => self.indexOf('2') !== index));
   //["1", "3", "4"]

//3、拼接两个数组
   //方式一
   var a = [1,2,3];
   var b = [...a,2];   // b = [1,2,3,2]
   //方式二
  var b = a.concat(b)

//4、字符串转数组
   var c = [...'abc']; // c = ['a','b','c']

//5、深拷贝数组的几种方式
   var b = [1,2];
   var a = b;
   b[0] = 2;
   console.log(a,b);  //a和b都变成[2,2]
   //方式一:
   var b = [1,2];
   var a = [...b];
   b[0] = 2;
   console.log(a,b);  // a = [1,2]; b = [2,2]

   //方式二:
   var b = [1,2];
   var a = JSON.parse(JSON.stringify(b)); //如果数组元素为对象,且对象有方法会导致方法丢失
   console.log(a,b);  // a = [1,2]; b = [2,2]

   //方式三:
   var b = [1,2];
   var a = b.concat();
   b[0] = 2;
   console.log(a,b); // a = [1,2]; b = [2,2]

   //方式四
   var b = [1,2];
   var [...a] = b;
   b[0] = 2;
   console.log(a,b); // a = [1,2]; b = [2,2]

//6、拷贝一个对象
   var a = {
       a : 1,
       b : true,
       c : {
           c1 : 'ci'
       },
       d : [1,2],
       e : function () {
           console.log('123')
       }
   };

   //方式一:
   var b = {...a};
   a.a = 3;
   console.log(a,b);  //改变a.a不会影响b.a的值

   //方式二: 注意,次方式只能拷贝数据,如果原对象有方法,会直接丢失,
   var b = JSON.parse(JSON.stringify(a));

//7、 数组去重,js filter()方法ES5已存在,ES6之后里面可以嵌套箭头函数了,
   //方式一:使用Set:
    var str = 'foo';
    var set = new Set([1,2,3,1]);
    var arr = Array.from(set);
    console.log(arr);  //[1,2,3]

   //方式二:  //filter可以传三个值,分别是item,index,self,self是数组arr本身
   var arr = [1,2,3,2,1,'a','b','a'];
   var arr2 = arr.filter((item,index,self) => self.indexOf(item) === index);
   console.log(arr2);

   // 方式三:
   var arrUniqe = [1,2,3,2,1,'a','b','a'];
   Array.prototype.unique = function() {
       var a = this.concat();
       for(var i=0; i console.log(val)
   )

   //使用RxJS实现包含对象的数组去重,例如:
   import { from } from "rxjs/internal/observable/from";
   import { distinct } from "rxjs/operators";
   var a = [{id:1,name:'a'},{id:2,name:'b'},{id:2,name:'b'},{id:3,name:'b'}];
   //如果认为name相同时就为相同项,则:
   from(a).pipe(distinct(item =>
     item.name
   )).subscribe(
     val => console.log(val)  // {id:1,name:'a'},{id:2,name:'b'}
   );
   //如果认为name和id都相同时才为相同项,则:
   from(a).pipe(distinct(item =>
     item.name && item.id
   )).subscribe(
     val => console.log(val)    // {id:1,name:'a'},{id:2,name:'b'},{id:3,name:'b'}
   );

//8、数组对象去重
    方式一:
    let lists= [
        {id: 6, age: 16},
        {id: 7, age: 17},
        {id: 8, age: 18},
        {id: 9, age: 19},
        {id: 8, age: 18},
        {id: 9, age: 19},
    ];
    let list = lists.reduce((cur,next) => {
        //如果只要id相同就是同一个数据
        cur.filter((item)=> item.id === next.id).length === 0 && cur.push(next);
        //如果必须id和age都相同才认定是同一个数据
        //cur.filter((item)=> item.id === next.id && item.age=== next.age).length === 0 && cur.push(next);
        return cur;
    },[]);
    console.log(list);  //[{id: 6, age: 16},{id: 7, age: 17},{id: 8, age: 18},{id: 9, age: 19}]

//9、数组过滤:
   //1、过滤数组某些特征的值,ES5写法
   var list1=[
       {id:1,age:9},
       {id:2,age:14},
       {id:3,age:17},
       {id:4,age:1}
   ];
   var list2 = list1.filter(function (item) {
       if(item.age > 10) return item
   });
   console.log(list2);

   //2、ES6写法
   const list2 = list1.filter(item=>(
       item.age>10
   ));
   console.log(list2);

   //3、过滤掉空值,如:'',0,undefined
   var arr1 = [0,'',undefined,1,'a'];
   var arr2 = arr1.filter(item => item);
   console.log(arr2);  //[1,'a']

//10、js判断两个数组是否相等,包括普通数组和包含对象的数组
   //情况一:两个普通数组
   var a = [1,true,undefined,3];
   var b = [1,true,undefined,3];
   function diff(a,b) {  //这种方式只能对比两个是值的数组是否相等,如果数组的项是对象{},此方法失效
       var arr1 = [...a].sort();
       var arr2 = [...b].sort();
       return arr1.toString() == arr2.toString()
   }
   console.log(diff(a,b));

   //情况二:包含对象的两个数组
   var a = [{id:1,name:'a'},{id:2,name:'b'},{id:2,name:'b'}];
   var b = [{id:1,name:'a'},{id:2,name:'b'},{id:2,name:'b'}];
   function diff(a,b,key1,key2) {  //三个或者四个参数分别为两个数组,key1,key2分别为两个数组必须要相等的属性值,其他可以不等
       var arr1 = [...a];
       var arr2 = [...b];
       var diff = false;
       if(arr1.length == arr2.length){
           if(arr1.length <= 0){
               diff = true
           }else {
               for(var j=0;j item).length <= 0) diff = true;
           }
       }
       return diff
   }
   console.log(diff(a,b,'id','name'));

//11、两个数组a1(新),a2(旧),a1是重新变化后的数组,新数组a1和旧数组a2对比,key一样时,保留旧数组a2已经设置的其他项,其他用新数组a1的项,
        var a1 = [{k:'key1',v:''},{k:'key2',v:''},{k:'key4',v:''}];  //新数组
        var a2 = [{k:'key1',v:'name1'},{k:'key2',v:'name2'},{k:'key3',v:'name3'}];  //老数组
        function updateArr(a1,a2,key) { //三个参数,分别是新数组、老数组、要对比的必须一样的key,key一样,
            if(a1.length != 0 && a2.length != 0){
                for(var i=0;i

你可能感兴趣的:(JS优雅写法记录)