JS最適化のコツ
2187 ワード
1.if多条件判断
//
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {}
//
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {}
2.if…else…//
let test: boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
//
let test = x > 10;
3.Null、Unidefined、空の値検査//
if (first !== null || first !== undefined || first !== '') {
let second = first;
}
//
let second = first || '';
4.foreachサイクル//
for (var i = 0; i < testData.length; i++)
//
for (let i in testData)
//
for (let i of testData)
5.関数条件呼び出し//
function test1() { console.log('test1'); };
function test2() { console.log('test2'); };
var test3 = 1;
if (test3 == 1) { test1(); }
else { test2(); }
//
(test3 === 1? test1:test2)();
6.switch条件//
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// so on...
}
//
var data = {
1: test1,
2: test2,
3: test
};
data[anything] && data[anything]();
7.複数行の文字列//
const data = 'abc abc abc abc abc abc
\t'
+ 'test test,test test test test
\t'
//
const data = `abc abc abc abc abc abc
test test,test test test test`
8.暗黙的な戻り//
function getArea(diameter) {
return Math.PI * diameter
}
//
getArea = diameter => (
Math.PI * diameter;
)
9.複数の文字列を繰り返す//
let test = '';
for(let i = 0; i < 5; i ++) {
test += 'test ';
}
//
'test '.repeat(5);
10.べき乗//
Math.pow(2,3);
//
2**3 // 8
11.対象のkey、value値を取得するObject.keys()、Object.values()、Object.entries()
12.画像のローディング loading="lazy" :
![](image.png)
13.配列デ重量実現方案1. Set
const arr = [12,34,565,12,34,1,3,1]
const newArr = Array.from(new Set(arr))
console.log('newArr',newArr);