2021 年你需要了解的 17 个 JavaScript 优化技巧
你可能已经使用Javascript
开发工具很长时间了,但有时你可能没有及时了解它提供的最新、最棒的功能,而这些功能无需编写额外的代码就能解决你的问题。这些技巧可以帮助你编写简洁、优化的 JavaScript 代码。此外,这些主题还能帮助你为 2021 年的 JavaScript 面试做好准备。
在我发表了一篇关于4 分钟内你不知道的 8 个简洁 JavaScript 技能的文章之后,我在这里推出了一个新系列,介绍速记技巧,帮助你编写更干净、更优化的 JavaScript 代码。我的目的是介绍所有 JavaScript 最佳实践,例如速记和特性,作为前端开发人员我们必须知道这些,以使我们在 2021 年的生活更轻松。这是你必须知道的 JavaScript 编码备忘单2021
。
1. 多个条件
我们可以在数组中存储多个值,并且可以使用数组includes
方法。
//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
//logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
//logic
}
2. 如果 true ... else 简写
if-else
当我们的条件不包含更复杂的逻辑时,这是一个更好的捷径。我们可以简单地使用ternary operators
来实现这个简写。
// Longhand
let test= boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//or we can simply use
let test = x > 10;
console.log(test);
嵌套条件之后,我们得到如下所示的内容:
let x = 300,
let test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"
3. Null、Undefined、Empty 检查
当我们创建新变量时,有时我们想检查所引用变量的值是否为null
或undefined
。JavaScript 确实有一个非常好的简写来实现这些功能。
// Longhand
if (first !== null || first !== undefined || first !== '') {
let second = first;
}
// Shorthand
let second = first|| '';
4. 空值检查和分配默认值
let first = null,
let second = first || '';
console.log("null check", test2); // output will be ""
5. 未定义值检查和分配默认值
let first= undefined,
let second = first || '';
console.log("undefined check", test2); // output will be ""
6.foreach 循环简写
这是迭代的有用简写
// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (let i in testData) or for (let i of testData)
每个变量的数组
function testData(element, index, array) {
console.log('test[' + index + '] = ' + element);
}
[11, 24, 32].forEach(testData);
// prints: test[0] = 11, test[1] = 24, test[2] = 32
7. 比较回报
在语句中使用比较return
将避免我们的 5 行代码并将其减少到 1 行。
// Longhand
let test;
function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return callMe('test');
}
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
console.log(val);
}
// Shorthand
function checkReturn() {
return test || callMe('test');
}
8.短函数调用
我们可以使用来实现这些类型的函数ternary operator
。
// Longhand
function test1() {
console.log('test1');
};
function test2() {
console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
test1();
} else {
test2();
}
// Shorthand
(test3 === 1? test1:test2)();
9. 切换速记
我们可以将条件保存在key-value
对象中,并根据条件使用。
// Longhand
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// And so on...
}
// Shorthand
var data = {
1: test1,
2: test2,
3: test
};
data[anything] && data[anything]();
10. 多行字符串简写
当我们在代码中处理多行字符串时,我们可以这样做:
//longhand
const data = 'abc abc abc abc abc abc\n\t'
+ 'test test,test test test test\n\t'
//shorthand
const data = `abc abc abc abc abc abc
test test,test test test test`
11.隐式返回简写
通过使用arrow functions
,我们可以直接返回值而不需要写return
语句。
Longhand:
//longhand
function getArea(diameter) {
return Math.PI * diameter
}
//shorthand
getArea = diameter => (
Math.PI * diameter;
)
12.查找条件简写
如果我们有代码来检查类型,并且根据类型需要调用不同的方法,我们可以选择使用多个else ifs
或选择switch
,但如果我们有比这更好的简写呢?
// Longhand
if (type === 'test1') {
test1();
}
else if (type === 'test2') {
test2();
}
else if (type === 'test3') {
test3();
}
else if (type === 'test4') {
test4();
} else {
throw new Error('Invalid value ' + type);
}
// Shorthand
var types = {
test1: test1,
test2: test2,
test3: test3,
test4: test4
};
var func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();
13.Object.entries()
此功能有助于将对象转换为array of objects
。
const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** Output:
[ [ 'test1', 'abc' ],
[ 'test2', 'cde' ],
[ 'test3', 'efg' ]
]
**/
14. Object.values()
这也是 中引入的一个新功能,ES8
它执行与 类似的功能Object.entries()
,但没有键部分:
const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:
[ 'abc', 'cde']
**/
15. 多次重复一个字符串
为了重复相同的字符,我们可以使用for loop
并将它们添加到相同的字符中,loop
但如果我们有一个简写呢?
//longhand
let test = '';
for(let i = 0; i < 5; i ++) {
test += 'test ';
}
console.log(str); // test test test test test
//shorthand
'test '.repeat(5);
16. 强力速记
数学指数幂函数的简写:
//longhand
Math.pow(2,3); // 8
//shorthand
2**3 // 8
17. 数字分隔符
现在只需一个 即可轻松分隔数字_
。这将使处理大量数字的开发人员的工作更加轻松。
//old syntax
let number = 98234567
//new syntax
let number = 98_234_567
如果您想了解 JavaScript 最新版本的最新功能,(ES2021/ES12)
请查看以下内容:
1. replaceAll():返回一个新字符串,其中所有符合模式的匹配项都被新的替换词替换。
2.Promise.any():它接受 Promise 对象的可迭代对象,并且当一个 Promise 对象实现时,返回一个带有值的单个 Promise。
3.weakref:此对象持有对另一个对象的弱引用,但不会阻止该对象被垃圾收集。
4. FinalizationRegistry:当对象被垃圾收集时,允许您请求回调。
5.私有可见性:方法和访问器的修饰符:Private methods
可以用 来声明#
。
6. 逻辑运算符: && 和 || 运算符。
7. Intl.ListFormat:此对象启用语言敏感的列表格式。
8. Intl.DateTimeFormat:此对象支持语言敏感的日期和时间格式。
结论
更重要的是,我们已经掌握了使用现代 JavaScript 技术优化代码的 17 种方法。
👋让我们成为朋友吧!在Twitter和Instagram上关注我,获取更多相关内容。别忘了在Dev上关注我,获取最新内容。
注意安全🏠
文章来源:https://dev.to/blessinghirwa/17-javascript-optimization-tips-3gil