ホームページ  >  記事  >  ウェブフロントエンド  >  効率を上げるための20のJavaScript省略テクニックのまとめと共有

効率を上げるための20のJavaScript省略テクニックのまとめと共有

WBOY
WBOY転載
2022-01-13 18:11:201179ブラウズ

この記事では、効率を上げるための JavaScript の省略テクニックを 20 個まとめて共有します。

効率を上げるための20のJavaScript省略テクニックのまとめと共有

省略形のヒント

複数の変数を同時に宣言する場合、それらは次のように省略できます。 1 行

//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';

|| を使用します変数にデフォルト値を割り当てる演算子

本質は || 演算子の特性を利用することです。前の式の結果がブール値 false に変換されるとき、値は次の式の結果。

//Longhand
let imagePath;
let path = getImagePath();
if (path !== null && path !== undefined && path !== '') {
    imagePath = path;
} else {
    imagePath = 'default.jpg';
}
//Shorthand
let imagePath = getImagePath() || 'default.jpg';

&& 演算子を使用して if ステートメントを簡略化します。

たとえば、関数は特定の条件が true の場合にのみ呼び出されます。これは

と省略できます。
//Longhand
if (isLoggedin) {
    goToHomepage();
 }
//Shorthand
isLoggedin && goToHomepage();

分割を使用して 2 つの変数の値を交換する

let x = 'Hello', y = 55;
//Longhand
const temp = x;
x = y;
y = temp;
//Shorthand
[x, y] = [y, x];

アロー関数を使用して関数を単純化する

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

アロー関数と通常の関数の違いに注意する必要があります

文字列テンプレートを使用してコードを簡素化する

元の文字列連結の代わりにテンプレート文字列を使用する

//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' + 
            'ECMAScript specification. JavaScript is high-level,\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
            ECMAScript specification. JavaScript is high-level,
            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 オブジェクトの賢い使い方簡潔な構文

たとえば、属性名と変数名は同じで、直接 1 に短縮できます

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 += &#39;Hello &#39;;
}
console.log(str); // Hello Hello Hello Hello Hello
// Shorthand
&#39;Hello &#39;.repeat(5);
// 想跟你说100声抱歉!
&#39;sorry\n&#39;.repeat(100);

Math.pow() の代わりに 2 つのアスタリスクを使用します。

//Longhand
const power = Math.pow(4, 3); // 64
// Shorthand
const power = 4**3; // 64

Math.floor() の代わりに 2 つのチルダ演算子 (~~) を使用します。

//Longhand
const floor = Math.floor(6.8); // 6
// Shorthand
const floor = ~~6.8; // 6

~~ は単なる2147483647 未満の数値に適用可能

展開演算子 (...) を使用してコードを簡素化します

配列の結合を簡略化します

let arr1 = [20, 30];
//Longhand
let arr2 = arr1.concat([60, 80]); // [20, 30, 60, 80]
//Shorthand
let arr2 = [...arr1, 60, 80]; // [20, 30, 60, 80]

オブジェクトの単一レイヤーのコピー

let obj = {x: 20, y: {z: 30}};
//Longhand
const makeDeepClone = (obj) => {
  let newObject = {};
  Object.keys(obj).map(key => {
      if(typeof obj[key] === &#39;object&#39;){
          newObject[key] = makeDeepClone(obj[key]);
      } else {
          newObject[key] = obj[key];
      }
});
return newObject;
}
const cloneObj = makeDeepClone(obj);
//Shorthand
const cloneObj = JSON.parse(JSON.stringify(obj));
//Shorthand for single level object
let obj = {x: 20, y: &#39;hello&#39;};
const cloneObj = {...obj};

配列内の最大値と最小値を検索します

// Shorthand
const arr = [2, 8, 15, 4];
Math.max(...arr); // 15
Math.min(...arr); // 2

for in と for of を使用して通常の for ループを簡素化します

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 = &#39;jscurious.com&#39;;
//Longhand
str.charAt(2); // c
//Shorthand
str[2]; // c

オブジェクト属性の削除

let obj = {x: 45, y: 72, z: 68, p: 98};
// Longhand
delete obj.x;
delete obj.p;
console.log(obj); // {y: 72, z: 68}
// Shorthand
let {x, p, ...newObj} = obj;
console.log(newObj); // {y: 72, z: 68}

arr.filter(Boolean) を使用して配列メンバーの値をフィルタリングします falsey

let arr = [12, null, 0, &#39;xyz&#39;, null, -25, NaN, &#39;&#39;, undefined, 0.5, false];
//Longhand
let filterArray = arr.filter(function(value) {
    if(value) return value;
});
// filterArray = [12, "xyz", -25, 0.5]
// Shorthand
let filterArray = arr.filter(Boolean);
// filterArray = [12, "xyz", -25, 0.5]

[関連する推奨事項: JavaScript 学習チュートリアル]
#

以上が効率を上げるための20のJavaScript省略テクニックのまとめと共有の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はjuejin.imで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。