- console.log
我们现在有下面的代码:
const foo = { name:"tom", age:30, nervous:false }
const bar = { name:"dick", age:40, nervous:false }
const baz = { name:"harry", age:50, nervous:true }
坏代码
console.log(foo)
console.log(bar)
console.log(baz)
坏结果
好代码
console.log({foo, bar, baz})
console.log 带有css样式的代码
console.log("%c My Frieds",'color:orange;font-weight:bold')
输出在带表格的样式
console.table([foo, bar, baz])
统计脚本运行时间
console.time(looper)
let i =0;
while( i < 100000) { i++ }
console.timeEnd(looper)
追踪调用栈
let sayBye = ()=> console.trace("Bye, Bey, LiSi")
sayBye();
sayBye();
sayBye();
-
destructuring(解构赋值)
const turble = { name:"Bob", legs: 4, shell: true, type:"amphibious", 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){ let {name, meal, diet} = animal; return `Feed ${name} ${meal} kiols of ${diet}`; }
-
字符串模板
const horse = { name:"Topher", size:"large", skills:['jousting','racing'], age:7 }
坏代码:
let bio = horse.name + " is a " + horse.size + " horse"
好代码
const { name, size} = horse let bio = `${name} is a ${size} horse`
更进一步,纯函数写法
function horseAge(str, age){ const ageStr = age > 5 ? "old":"young" ; return `${str[0]}${ageStr} at ${age} years`; } const bio = horseAge`This horse is ${horse.age}`; console.log(bio)
-
扩展符的应用
对象类型
const pikachu = { name: "Pikachu" }; const stats = { hp: 30, attack: 60, defense: 45 }
坏代码
pikachu["hp"] = stats.hp; pikachu["attack"] = stats.attack; pikachu["defense"] = stats.defense; 或者 const lvl0 = Object.assign(pikachu, stats); const lvl1 = Object.assign(pikachu, { hp: 45 });
好代码
const lvl0 = {...pikachu,...stats}
数组类型
let pockmon = ['Arbok', 'Raichu', 'Sandshrw'];
坏代码
pockmon.push("Bulbasaur") pockmon.push("Metapod") pockmon.push("Weedle")
好代码
pockmon = [...pockmon, "Bulbasaur", "Metapod","Weedle"] // Shift pockmon = ["Bulbasaur", "Metapod","Weedle",...pokemon]
-
循环
const orders = [500, 30, 99, 15, 223];
坏代码
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-await
const random = () => { return Promise.resolve(Math.random()); };
坏代码
const sumRandomAsyncNums = () => { let first; let second; let 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(); // or const randos = Promise.all([random(), random(), random()]); for (const r of await randos) { console.log(r); } };