Set是 ES6 中引入的新数据结构,类似于Map。 它允许您将不同的值存储到类似于其他编程语言的列表中 Java,C#。
创建集合
使用Set类型和new关键字在 TypeScript 中创建Set。
let mySet = new Set();
从集合中添加/检索/删除值
set.add()– 在Set中添加值的方法。set.has()– 检查Set中是否存在值。set.delete()– 从Set中删除一个值。set.size– 将返回Set的大小。
let diceEntries = new Set();//Add ValuesdiceEntries.add(1);diceEntries.add(2);diceEntries.add(3);diceEntries.add(4).add(5).add(6); //Chaining of add() method is allowed//Check value is present or notdiceEntries.has(1); //truediceEntries.has(10); //false//Size of SetdiceEntries.size; //6//Delete a value from setdiceEntries.delete(6); // true//Clear whole SetdiceEntries.clear(); //Clear all entries
遍历集合
使用'for...of'循环迭代Set值。
let diceEntries = new Set();diceEntries.add(1).add(2).add(3).add(4).add(5).add(6);//Iterate over set entriesfor (let currentNumber of diceEntries) {console.log(currentNumber); //1 2 3 4 5 6}// Iterate set entries with forEachdiceEntries.forEach(function(value) {console.log(value); //1 2 3 4 5 6});
将我的问题放在评论部分。
学习愉快!
