标签:lse pat 今天 average 数字 自己的 运算符 pre else
每一位程序员不想让自己的代码写的特别冗余,能用一行解决的事情坚决不写两行。今天给大家分享几个常见的简写方式
1、变量的声明
//Longhand let x; let y = 20; //Shorthand let x, y = 20;
2、给多个变量赋值
//Longhand let a, b, c; a = 5; b = 8; c = 12; //Shorthand let [a, b, c] = [5, 8, 12];
3、赋默认的值
//Longhand
let imagePath;
let path = getImagePath();
if(path !== null && path !== undefined && path !== ‘‘) {
imagePath = path;
} else {
imagePath = ‘default.jpg‘;
}
//Shorthand
let imagePath = getImagePath() || ‘default.jpg‘;
4、与 (&&) 短路运算
如果你只有当某个变量为 true 时调用一个函数,那么你可以使用与 (&&)短路形式书写。
//Longhand
if (isLoggedin) {
goToHomepage();
}
//Shorthand
isLoggedin && goToHomepage();
5、在多个条件中查找是否存在条件 ,我们可以将所有的值放到数组中,然后使用indexOf()或includes()方法。
/Longhand
if (value === 1 || value === ‘one‘ || value === 2 || value === ‘two‘) {
// Execute some code
}
// Shorthand 1
if ([1, ‘one‘, 2, ‘two‘].indexOf(value) >= 0) {
// Execute some code
}
// Shorthand 2
if ([1, ‘one‘, 2, ‘two‘].includes(value)) {
// Execute some code
}
6、 字符串转成数字
有一些内置的方法,例如parseInt和parseFloat可以用来将字符串转为数字。我们还可以简单地在字符串前提供一个一元运算符 (+) 来实现这一点。
//Longhand let total = parseInt(‘453‘); let average = parseFloat(‘42.6‘); //Shorthand let total = +‘453‘; let average = +‘42.6‘;
7、找出数组中的最大和最小数字
// Shorthand const arr = [2, 8, 15, 4]; Math.max(...arr); // 15 Math.min(...arr); // 2
以上是常见的一些简写技巧,留着备用参考
标签:lse pat 今天 average 数字 自己的 运算符 pre else
原文地址:https://www.cnblogs.com/agen-su/p/14416123.html