让你到点下班的JS简写技巧

1、对于多值匹配可将所有值放在数组中通过数组方法来简写

//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 
}

2、使用repeat()方法简化重复一个字符串

//Longhand
let str = '';
for(let i = 0; i < 4; i ++) {
  str += 'Hello ';
}
console.log(str); // Hello Hello Hello Hello 
// Shorthand
'Hello '.repeat(4);
// 99次感谢!
'Thank\n'.repeat(99);

3、使用一元运算符简化字符串转数字

//Longhand
let total = parseInt('123');
let average = parseFloat('34.5');
//Shorthand
let total = +'123';
let average = +'34.5';

4、使用for in和for of来简化普通for循环

let arr = [9, 19, 29, 39];
//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]);
}

5、简化获取字符串中的某个字符

let str = 'jscurious.com';
//Longhand
str.charAt(4); // c
//Shorthand
str[4]; // c

6、使用双星号代替Math.pow()

//Longhand
const power = Math.pow(1, 2); // 64
// Shorthand
const power = 1**2; // 64

7、适用箭头函数简化函数

//Longhand
function add(num1, num2) {
  return num1 + num2;
}
//Shorthand
const add = (num1, num2) => num1 + num2;