如何让代码写的更安全高效一直是程序员的不懈追求!在解决问题的同时,简介清爽,逻辑严谨的代码会让程序员更带光环。
简书亦有简码
1.使用三元运算符赋值
❌ a > b ? foo = 'apple' : foo = 'ball'; ✔️ foo = a > b ? 'apple' : 'ball';
2.利用三元运算给指定的对象的不同属性赋值
❌ c > d ? a.foo = 'apple' : a.bar = 'apple'; ✔️ a = { [c > d ? 'foo' : 'bar']: 'apple' };
3.同时导出多个变量
❌ export const foo; export const bar; export const kip; ✔️ export const foo, bar, kip;
4.从一个对象的多个属性值给变量声明并赋值
❌ const a = foo.x, b = foo.y; ✔️ const { ['x']: a, ['y']: b } = foo;
5.一个数组多多个变量赋值
❌ let a = foo[0], b = foo[1]; ✔️ let [a, b] = foo;
6.从DOM中获取多个元素
❌ const a = document.getElementById('a'), b = document.getElementById('b'), c = document.getElementById('c'); d = document.getElementById('d'); ✔️ const elements = {}; ['a', 'b', 'c', 'd'].forEach(item => elements = { ...elements, [item]: document.getElementById(item) }); const { a, b, c, d } = elements;
7.用逻辑运算代替简单的条件语句
❌ if (foo) { doSomething(); } ✔️ foo && doSomething();
8.有条件的参数传值
❌ if(!foo){ foo = 'apple'; } bar(foo, kip); ✔️ bar(foo || 'apple', kip);
9.解决0多书写的问题
❌ const SALARY = 150000000, TAX = 15000000; ✔️ const SALARY = 15e7, TAX = 15e6;
10.给多个变量赋同一个值
❌ a = d; b = d; c = d; ✔️ a = b = c = d;