よく使用されるいくつかのjsのヒント

1.一意の値をフィルタリングする

SetオブジェクトタイプはES6で導入されました。展開操作と一緒に...一緒に使用して、一意の値のみを持つ新しい配列を作成できます。

const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Result: [1, 2, 3, 5]

ES6より前は、一意の値を分離するには、これよりもはるかに多くのコードが必要でした。

この手法は、undefined、null、boolean、string、numberなどの基本的な型を含む配列に適しています。(オブジェクト、関数、またはその他の配列を含む配列がある場合は、別のアプローチが必要です!)

2.ブール値に変換

const isTrue  = !0;
const isFalse = !1;
const alsoFalse = !!0;
console.log(isTrue); // Result: true
console.log(typeof true); // Result: "boolean"

 3.文字列に変換します

const val = 1 + "";
console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"

 4.数値に変換する

加算演算子+を使用して、反対の効果をすばやく実現します。

let int = "15";
int = +int;
console.log(int); // Result: 15
console.log(typeof int); Result: "number"

これは、以下に示すようにブール値を数値に変換するためにも使用できます

console.log(+true);  // Return: 1
 console.log(+false); // Return: 0

5.配列の切り捨て

配列の最後から値を削除したい場合は、splice()を使用するよりも高速な方法があります。

たとえば、元の配列のサイズがわかっている場合は、次のようにその長さプロパティを再定義できます。

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4;
console.log(array); // Result: [0, 1, 2, 3]

 これは特に簡潔な解決策です。ただし、slice()メソッドの方が高速であることがわかりました。速度が主な目標である場合は、以下の使用を検討してください。

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);
console.log(array); // Result: [0, 1, 2, 3]

6.配列の最後のアイテムを取得します

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]

7.JSONコードをフォーマットします

最後に、以前にJSON.stringifyを使用したことがあるかもしれませんが、JSONのインデントにも役立つことに気づきましたか?

stringify()メソッドには、2つのオプションのパラメーターがあります。表示されたJSONとスペース値をフィルター処理するために使用できるreplacer関数です。

console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));
// Result:
// '{
//     "alpha": A,
//     "beta": B
// }'

おすすめ

転載: blog.csdn.net/AN0692/article/details/105806460