高级前端工程师如何避免写出屎一样的代码(一)?

1,753 阅读2分钟

用ES新特性来优化你的javaScript代码

更优雅地使用console


const foo = {name: 'zds', age: 12};
const bar = {name: 'dj', age: 11};

💩
console.log(foo)
console.log(bar)
👍
  • 使用对象表示
console.log({foo, bar})

  • 使用css样式
console.log('%c my friends', 'color: orange; font-weight: bold')
console.log({foo, bar})

image.png

  • 使用表格展示
console.table([foo, bar])

image.png

  • 显示代码执行耗时
console.time('code start')
while (i < 10000) { i++ }
console.timeEnd('code end')
  • 显示调用的日志
	const deleteMe =() => {console.trace('我删库了')}
	deleteMe()
	deleteMe()

image.png

解构

const turtle = {
	name: 'pkq',
	legs: 4,
	shell: true,
	type: 'land',
	meal: 10,
	diet: 'berries'
}
💩

function feed(animal) {
	return `Feed ${animal.name} ${animal.meal} kiols of ${animal.diet}`
}
👍
  • 将参数解构

function feed({ name, meal, diet }) {
	return `Feed ${name} ${meal} kiols of ${diet}`;
}

//或者

function feed(animal) {
    const { name, meal, diet } = animal;
	return `Feed ${name} ${meal} kiols of ${diet}`;
}

模板字符串

const horse = {
    name: 'Tom',
    size: 'large',
    skills: ['jousting', 'racing'],
    age: 7
}

💩
let intro = horse.name + 'is a ' + horse.size + ' horse silled in ' + hosre.skills.join('&');

👍
const {name, size, skills} = horse;
vonst intro = `${name} is a ${size}  horse silled in ${hosre.skills.join('&')}`;
function horseAge(str, age) {
   
    const ageStr = age > 5 ? 'old' : 'young';
    return `${str[0]}${ageStr} at ${age} years`;
}

const intro2 = horseAge`This horse is ${horse.age}`;

image.png

延展操作符

const pikachu = { name: 'Pikachu'};
const status = {hp: 40, attack: 60. defense: 45};

const pokemon = ['a', 'b', 'c', 'd']


💩
pikachu['hp'] = status.hp;
pikachu['attack'] = status.attack;
pikachu['defense'] = status.defense;

pokemon.push('e');
pokemon.push('f');
pokemon.push('g');


const lv10 = Object.assign(pikachu, status);

const lv11 = Object.assign(pikachu, { hp: 45});


👍
const lv10 = { ...pikachu, ...status};

const lv11 = { ...pikachu, hp: 45};

//push
pokemon = [...pokemon, 'e', 'f', 'g'];

//shit
pokemon = [ 'e', 'f', 'g', ...pokemon];

循环

const orders = [300, 200, 30, 18, 476];

💩
const total = 0;
const withTax = [];
const highValue = [];
for (i = 0; i< orders.length; i++) {
    total += orders[i];
    
    withTax.push(orders[i]*1.1);
    
    if(orders[i] > 100) {
        highValue.push(orders[i])
    }
}
👍
const total = orders.reduce((acc, cur) => acc + cur);
const withTax = orders.map(v => v*1.1);
const highValue = orders.filter(v => v > 100)

async异步转同步

const random = () => {
    return Promise.resolve(Math.random())
}

💩
const sumRandomAsyncNums = () => {
    let first, second, third;
    
    return random()
        .then(v=>{
            first = v;
            return random();
        })
        .then(v=>{
            second = v;
            return random();
        })
        .then(v=>{
            third = v;
            return random();
        })
        
}

👍
const sumRandomAsyncNums = async() => {
    
    const first = await random();
    const second = await random();
    const third = await random();
   
    console.log(`result is ${first + second + third}`)
}

更高效地书写CSS

学习使用盒模型

🤗

在使用浏览器调试样式时,可以直接使用元素的盒模型来调节宽高、边距、边框的大小

双击对应的数值,就可以修改,并实时查看效果

image.png

使用flex代替position定位

🙁

.box {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

😊

.box {
    display: flex;
    justify-content: center;
    align-items: center;
}

Grid布局是非常Great的

<div class="box">
    <i>😝</i>
    <i>😝</i>
    <i>😝</i>
    <i>😝</i>
    <i>😝</i>
    <i>😝</i>
</div>

.box {
    display: grid;
    grid-template-columns: 1fr 500px 1fr;
    grid-template-rows: 100px 200px;
    place-items: center;
}

clamp函数真的很棒

www.cnblogs.com/lvonve/p/13…

🙁

这种写法真的让人裂开

image.png

😊

image.png

可以尝试使用表情包作为className(在不被老板屌的情况下)

🤗

image.png

定义横纵比属性

🙁

image.png

😊

image.png

使用变量防止产品经理不必要的“变量”

🙁


h1 {
    color: red;
}

p {
    color: red;
}

a {
    color: red;
}

😊


:root {
    --text-color: red;
}

h1 {
    color: var(--text-color);
}

p {
    color: var(--text-color);
}

a {
    --text-color: green; <!--override-->
    color: var(--text-color);
}


:root {
    --r:255;
    --g:0;
    --b:0;
    --a:1;
    --text-color: rgba(var(--r),var(--g), var(--b), var(--a));
}

h1 {
    color: var(--text-color);
}

p {
    color: var(--text-color);
}

a {
    --text-color: green; <!--override-->
    color: var(--text-color);
}

使用css的计算属性

🤗

image.png

深度利用浏览器的F12

🤗

image.png