Avoid code redundancy, learn js code optimization skills

How to make your code look concise and clear, learn the following js code optimization techniques. At present, these sorted out are very common in development, and many more will be added later:

1. Reverse string:

const reverse = str => str.split('').reverse().join('');

2. Keep decimal places:
//n value, fixed reserved digits

const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);

3. Scroll to the top of the page:

const goToTop = () => window.scrollTo(0, 0);

4. Multi-condition if judgment
// Redundant
if (x ==='abc' || x ==='def' || x ==='ghi' || x ==='jkl') {}
/ / Concise

if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {}

5.if…else…
// 冗余
let test: boolean;
if (x > 100) {
test = true;
} else {
test = false;
}

// concise

let test = x > 10;

6. Switch statement judgment
// redundant
switch (data) { case 1: test1(); break;


case 2:
test2();
break;

case 3:
test();
break;
// so on…
}

// concise

var data = {
  1: test1,
  2: test2,
  3: test
};

data[anything] && data[anything]();

7. Repeat the string many times:
// redundant
let test ='';
for(let i = 0; i <5; i ++) { test +='test'; }

// concise

'test '.repeat(5);

Guess you like

Origin blog.csdn.net/qq_43237014/article/details/113387688
Recommended