多个if 语句 => 把多个值放在一个数组中,然后调用数组的 includes 方法。
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
}
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
}
if-else 条件 => 三元运算符来实现这种简化
// Longhand
let test: boolean
if (x > 100) {
test = true
} else {
test = false
}
// Shorthand
let test = (x > 10) ? true : false
//or we can use directly
let test = x > 10
console.log(test)
变量声明
//Longhand
let test1
let test2 = 1
//Shorthand
let test1, test2 = 1
null、undefined 和空值检查
if (test1 !== null || test1 !== undefined || test1 !== '') {
let test2 = test1;
}
let test2 = test1 || '';
给多个变量赋值
//Longhand
let test1, test2, test3
test1 = 1
test2 = 2
test3 = 3
//Shorthand
let [test1, test2, test3] = [1, 2, 3]
简便的赋值操作符
// Longhand
test1 = test1 + 1
test2 = test2 - 1
test3 = test3 * 20
// Shorthand
test1++
test2--
test3 *= 20
if 判断值是否存在
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
if (test1)
用于多个条件判断的 && 操作符
if (test1) {
callMethod();
}
test1 && callMethod();
箭头函数
function add(a, b) {
return a + b;
}
const add = (a, b) => a + b;
function callMe(name) {
console.log('Hello', name);
}
callMe = name => console.log('Hello', name);
switch 简化
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
}
var data = {
1: test1,
2: test2,
3: test
};
data[something] && data[something]();
指数表示法
// Longhand
for (var i = 0; i < 10000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e4; i++) {
默认参数值
//Longhand
function add(test1, test2) {
if (test1 === undefined)
test1 = 1
if (test2 === undefined)
test2 = 2
return test1 + test2
}
//shorthand
add = (test1 = 1, test2 = 2) => (test1 + test2)
add() //output: 3
延展操作符简化
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test);
模板字面量
//longhand
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'
//shorthand
const welcome = `Hi ${test1} ${test2}`
将字符串转成数字
//Longhand
let test1 = parseInt('123')
let test2 = parseFloat('12.3')
//Shorthand
let test1 = +'123'
let test2 = +'12.3'
变量解构
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
const { test1, test2, test3 } = this.data;
数组 find 简化
const data = [{
type: 'test1',
name: 'abc'
},
{
type: 'test2',
name: 'cde'
},
{
type: 'test1',
name: 'fgh'
},
]
function findtest1(name) {
for (let i = 0
if (data[i].type === 'test1' && data[i].name === name) {
return data[i]
}
}
}
//Shorthand
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh')
console.log(filteredData)
indexOf 的按位操作简化
if(arr.indexOf(item) > -1) {
}
if(arr.indexOf(item) === -1) {
}
if(~arr.indexOf(item)) {
}
if(!~arr.indexOf(item)) {
}
双重按位操作
Math.floor(1.9) === 1
~~1.9 === 1
查找数组的最大值和最小值
const arr = [1, 2, 3]
Math.max(…arr)
Math.min(…arr)