chenfei-hnu / Blog

个人整理的跟前端相关的文档 ( This is some front-end development related documentation )
9 stars 2 forks source link

代码简洁优化技巧 #46

Open chenfei-hnu opened 4 years ago

chenfei-hnu commented 4 years ago

整理项目中能够用到的简洁优化同时保证可读性的代码技巧

基础常用措施

const table = tableVisible ? <Table/> : null;
const fn = (a,b) => a+b;
const [last, ...initial] = [1, 2, 3];
`${prev} - ${after}`

其他技巧

  1. 数组去重

    
    var unique = Array.from(new Set(fruits));

var unique = […new Set(fruits)];


2. 替换数组中的特定位置值

var fruits = ["1", "2", "3", "4"];

fruits.splice(0, 2, "11", "22"); // 替换前面2项


3. 格式化数组

var friends = [ { name: "John", age: 22 }, { name: "Peter", age: 23 }, { name: "Mark", age: 24 }, { name: "Maria", age: 22 }, { name: "Monica", age: 21 }, { name: "Martha", age: 19 }, ]

var friendsNames = Array.from(friends, ({name}) => name); friends.map((item) => item.name);


4.初始化填充数组

var newArray = new Array(10).fill("0");


5. 截断数组

const arr = [11, 22, 33, 44, 55, 66]; arr.length = 3; console.log(arr); //=> [11, 22, 33]


6. 取交集

var duplicateArr = arr1.filter(item => arr2.includes(item));


7. 数组值累加

var nums = [1, 5, 2, 6]; var sum = nums.reduce((x, y) => x + y);


8、解构赋值

1). 解构数组 const [last, ...initial] = [1, 2, 3];

2).解构对象 const { a, ...rest } = { a: 1, b: 2, c: 3 }

3).参数传值 function add(a, b, c){ return a + b + c; } const args = [1, 2, 3]; add(...args);

4).对象遍历 for (let [key, value] of Object.entries(obj)) { console.log(key + ':' + value); } Object.entries({}).forEach(([key, value]: any) => { console.log(key + ':' + value); }); // Object.entries(返回数据的顺序是不确定

5).交换变量 [a, b] = [b, a]

6). 浅拷贝 const arrClone = [...arr] const objClone = { ...obj }

7). 数组转对象 const newObj = {...arr}

8). 合并数组,对象 const newObj = {...obj1, obj2}; const newArr = {...arr1, arr2};


9. curry 使用箭头函数实现柯里化

const add = a => { return b => c + d; }; const add2 = add(2); add2(1);

var greet = function(greeting, name) { return greeting + ' ' + name; }; const sayHelloTo = name => greet('hello', name); sayHelloTo('fred');


10、运算符

+运算符 -  转化为number类型

+'1.1' // 1.1

+[111] // 111

+[1, 2] // NaN

+true // 1


 ?判断运算符 - 对象存在属性或者方法时执行

modal?.parentNode?.removeChild(modal);


!! 运算符 - 转化为boolean类型

!!0 // false

!!{} // true


11.JSON.stringify 格式化

JSON.stringify({"websocket":true,,"cookie_needed":false,"entropy":1287694745},null,'\t'); "{ "websocket": true, "cookie_needed": false, "entropy": 1287694745 }"


12.避免多条件并列

if (status === 'process' || status === 'wait' || status === 'fail') { doSomething() }

const enum = ['process', 'wait', 'fail'] if (enum.includes(status)) { doSomething() }


13.利用call,apply灵活使用其他类型的原型方法 

Math.max.apply(null, [1,2,3]) // 为数组添加max,min函数

var a={length:2,0:'0',1:'1'}; // 类数组 console.log(Array.prototype.slice.call(a,0,1)); // '0'



14.最喜欢的 215 条 JS Util 方法-最多一行
https://1loc.dev/