セット
セットは、重複する値を含まない、順序付けされていない一連のデータ セットです。
方法
1. add() でメンバーを追加します
const s = new Set();
s.add(1).add(2).add(1);
console.log(s);
重複した値は追加できません
2. has()は特定のメンバーが含まれるかどうかを判定します
const s = new Set();
s.add(1).add(2).add(1);
console.log(s.has(1));//true
console.log(s.has(3));//false
3. delete は指定されたメンバーを削除し、clear() はすべてのメンバーを削除します。
const s = new Set();
s.add(1).add(2).add(1);
s.delete(1)
console.log(s);//Set(1) { 2 }
4. forEach は、コレクションに追加された順序でメンバーを走査します。
const s = new Set();
s.add(1).add(2).add(3);
s.forEach(function(value){
console.log(value);
});
コンストラクターのパラメーターを設定する
1. アレイ
const s = new Set([1,2,3]);
console.log(s);
//Set(3) { 1, 2, 3 }
2.文字列
const s = new Set('hello');
console.log(s);//Set(4) { 'h', 'e', 'l', 'o' }
3、引数
function func() {
console.log(new Set(arguments));//Set(2) { 1, 2 }
}
func(1,2,1);
セットを使用する場合
1. 配列または文字列を重複排除する場合
console.log([...new Set([1,2,1])]);//[ 1, 2 ]
const s = new Set('abbacbd');
console.log([...s].join(""));//abcd
2. サブスクリプトでアクセスする必要はなく、トラバーサルのみが必要です
3. Set が提供するメソッドとプロパティを使用するため (add、delete、clear、forEach size など)
地図
マップとオブジェクトはどちらもキーと値のペアのコレクションです
。マップとオブジェクトの違い: オブジェクトは通常、文字列をキーとして使用します。
基本データ型: 数値、文字列、ブール値、未定義、null。
参照データ型: オブジェクト ([]、 { }、関数、Set、Map など)
上記すべてを Map キーとして使用できます。
方法
1. set() は新しいメンバーを追加します
const m = new Map();
m.set('age',18).set(true, 'true').set('age',20)
console.log(m);//Map(2) { 'age' => 20, true => 'true' }
//覆盖原来的值
2. get() でメンバーを取得します
const m = new Map();
m.set('age',18).set(true, 'true').set('age',20)
console.log(m.get('age'));//20
//get 获取不存在的成员,返回undefined
console.log(m.get('true'));//undefined
console.log(m.get(true));//true
2. has() に特定の値が含まれているかどうか
const m = new Map();
m.set('age',18).set(true, 'true').set('age',20)
console.log(m.has('age'));//true
3. clear() はすべてのデータをクリアします
4. forEach は、コレクションに追加された順序でメンバーを走査します。
コールバック関数の最初のパラメータは値で、2 番目のパラメータはキーです。これは変更することもできます他のパラメータ名に。
const m = new Map();
m.set('age',18).set('name', 'zhangsan').set('age',20)
m.forEach(function(value,key){
console.log(key+'=>'+value)
});
console.log('------------------');
m.forEach(function(one,two){
console.log(two+'=>'+one)
});
マップコンストラクターパラメータ
1. 2次元配列
console.log(new Map([
['name', 'alex'],
['age',18]
])
);
//Map(2) { 'name' => 'alex', 'age' => 18 }
2.
キーと値はセット、マップなどにも反映される必要があります。
const s = new Set([
['name','alex'],
['age',18]
]);
console.log(new Map(s));//Map(2) { 'name' => 'alex', 'age' => 18 }
console.log(s);//Set(2) { [ 'name', 'alex' ], [ 'age', 18 ] }
マップを使用する場合
1. キー -> 値の構造のみが必要な場合、またはキーとして文字列以外の値が必要な場合は、Map を使用する方が適切です 2. forEach for in
3.
size