//Longhand
let x;
let y = 20;
//Shorthand
let x, y = 20;
复制代码
利用解构,可为多个变量同时赋值
//Longhand
let a, b, c;
a = 5;
b = 8;
c = 12;
//Shorthand
let [a, b, c] = [5, 8, 12];
复制代码
巧用三元运算符简化if else
//Longhand
let marks = 26;
let result;
if (marks >= 30) {
result = 'Pass';
} else {
result = 'Fail';
}
//Shorthand
let result = marks >= 30 ? 'Pass' : 'Fail';
复制代码
//Longhand
console.log('You got a missed call from ' + number + ' at ' + time);
//Shorthand
console.log(`You got a missed call from ${number} at ${time}`);
复制代码
多行字符串也可使用字符串模板简化
//Longhand
console.log('JavaScript, often abbreviated as JS, is a\n' +
'programming language that conforms to the \n' +
'often just-in-time compiled, and multi-paradigm.'
);
//Shorthand
console.log(`JavaScript, often abbreviated as JS, is a
programming language that conforms to the
often just-in-time compiled, and multi-paradigm.`
);
复制代码
对于多值匹配,可将所有值放在数组中,通过数组方法来简写
//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
}
复制代码
巧用ES6对象的简洁语法
例如,当属性名和变量名相同时,可直接缩写为一个
let firstname = 'Amitav';
let lastname = 'Mishra';
//Longhand
let obj = {firstname: firstname, lastname: lastname};
//Shorthand
let obj = {firstname, lastname};
复制代码
使用一元运算符简化字符串转数字
//Longhand
let total = parseInt('453');
let average = parseFloat('42.6');
//Shorthand
let total = +'453';
let average = +'42.6';
复制代码
使用repeat()方法简化重复一个字符串
//Longhand
let str = '';
for(let i = 0; i < 5; i ++) {
str += 'Hello ';
}
console.log(str); // Hello Hello Hello Hello Hello
// Shorthand
'Hello '.repeat(5);
// 想跟你说100声抱歉!
'sorry\n'.repeat(100);
复制代码
使用双星号代替Math.pow()
//Longhand
const power = Math.pow(4, 3); // 64
// Shorthand
const power = 4**3; // 64
复制代码
let arr = [10, 20, 30, 40];
//Longhand
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
//Shorthand
//for of loop
for (const val of arr) {
console.log(val);
}
//for in loop
for (const index in arr) {
console.log(arr[index]);
}
复制代码
简化获取字符串中的某个字符
let str = 'jscurious.com';
//Longhand
str.charAt(2); // c
//Shorthand
str[2]; // c
复制代码