本文翻译自 18 JavaScript Tips : You Should Know for Clean and Efficient Code,作者:Shefali, 略有删改。
在这篇文章中,我将分享18个JavaScript技巧,以及一些你应该知道的示例代码,以编写简洁高效的代码。
让我们开始吧!
箭头函数
可以使用箭头函数来简化函数声明。
function add(a, b) { return a + b; } // Arrow function const add = (a, b) => a + b;
Array.from()
Array.from()方法可用于将任何可迭代对象转换为数组。
const str = "Hello!"; const arr = Array.from(str); console.log(arr); //Output: ['H', 'e', 'l', 'l', 'o', '!']
使用console.table显示数据
如果您希望在控制台中组织数据或以表格格式显示数据,则可以使用console.table()。
const person = { name: 'John', age: 25, profession: 'Programmer' } console.table(person);
输出效果:
图片
使用const和let
对于不会被重新分配的变量使用const
const PI = 3.14; let timer = 0;
使用解构提取对象属性
通过使用解构从对象中提取属性,可以增强代码的可读性。
const person = { name: 'John', age: 25, profession: 'Programmer' } //Instead of this