常用的JavaScript简写技巧
2021-10-31 本文已影响0人
small_zeo
JavaScript 的简写技巧
- 变量声明
let x;
let y = 8;
// 简写
let x, y = 8;
- 多个变量赋值
let a, b, c;
a = 1;
b = 2;
c = 3;
// 简写
let [a, b, c] = [1, 2, 3];
- 三元运算符
if(a = true){
console.log(1);
}else{
console.log(2);
}
// 简写
a = true ? console.log(1) : console.log(2);
- 赋默认值
let imagePath;
let path = getImagePath();
if(path !== null && path !== undefined && path !== '') {
imagePath = path;
} else {
imagePath = 'default.jpg';
}
// 简写
let imagePath = getImagePath() || 'default.jpg';
- 与运算符 (&&)
if (isLoggedin) {
goToHomepage();
}
// 简写
isLoggedin && goToHomepage();
- 交换两个变量
let x = 'Hello', y = "javaScript";
const temp = x;
x = y;
y = temp;
// 简写
[x, y] = [y, x];
- 箭头函数
function add(num1, num2) {
return num1 + num2;
}
// 简写
const add = (num1, num2) => num1 + num2;
- 模板字符串
console.log('You got a missed call from ' + number + ' at ' + time);
// 简写
console.log(`You got a missed call from ${number} at ${time}`);
- 多条件检查
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
// Execute some code
}
// 简写方法 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) { // indexOf 返回下标 没有则返回-1
// Execute some code
}
// 简写方法 2
if ([1, 'one', 2, 'two'].includes(value)) { // includes 返回 turn / false
// Execute some code
}
- 对象属性复制
let firstname = 'Amitav';
let lastname = 'Mishra';
let obj = {firstname: firstname, lastname: lastname};
// 简写
let obj = {firstname, lastname}; // es6中的速写属性
- 字符串转换成数字
let total = parseInt('453'); // 整型数字
let average = parseFloat('42.6'); // 浮点型数字 即 带小数点的数
// 简写
let total = +'453';
let average = +'42.6';
- 重复一个字符串多次
let str = '';
for(let i = 0; i < 5; i ++) {
str += 'Hello ';
}
console.log(str); // Hello Hello Hello Hello Hello
// 简写
'Hello'.repeat(5);
- 优雅的获取数组中的最大值 同理也可以求得最小值
var arr1 = [1,2,3,4,999,1999];
Math.max(...arr); // 1999
Math.min(...arr); // 1
- 指数幂
const power = Math.pow(4, 3); // 64
// Shorthand
const power = 4**3; // 64
- 双非位运算符 (~~)
const floor = Math.floor(6.8); // 6
// 简写
const floor = ~~6.8; // 6