📜  TypeScript集

📅  最后修改于: 2021-01-11 12:38:38             🧑  作者: Mango

打字稿集

TypeScript集是在ES6版本的JavaScript中添加的新数据结构。它使我们可以像其他编程语言一样,将不同的数据(每个值仅出现一次)存储到List中。集是有点类似于地图,但它仅存储密钥,而不是键值对。

创建集

我们可以如下创建一个集合

let mySet = new Set();

设定方法

TypeScript设置方法在下面列出。

SN Methods Descriptions
1. set.add(value) It is used to add values in the set.
2. set.has(value) It returns true if the value is present in the set. Otherwise, it returns false.
3. set.delete() It is used to remove the entries from the set.
4. set.size() It is used to returns the size of the set.
5. set.clear() It removes everything from the set.

我们可以从以下示例中了解set方法。

let studentEntries = new Set();
 
//Add Values
studentEntries.add("John");
studentEntries.add("Peter");
studentEntries.add("Gayle");
studentEntries.add("Kohli"); 
studentEntries.add("Dhawan"); 

//Returns Set data
console.log(studentEntries); 
 
//Check value is present or not
console.log(studentEntries.has("Kohli"));      
console.log(studentEntries.has(10));      
 
//It returns size of Set
console.log(studentEntries.size);  
 
//Delete a value from set
console.log(studentEntries.delete("Dhawan"));    
 
//Clear whole Set
studentEntries.clear(); 

//Returns Set data after clear method.
console.log(studentEntries);

输出:

当我们执行上述代码片段时,它将返回以下输出。

设置方法的链接

TypeScript set方法还允许链接add()方法。我们可以从以下示例中了解它。

let studentEntries = new Set();
 
//Chaining of add() method is allowed in TypeScript
studentEntries.add("John").add("Peter").add("Gayle").add("Kohli");

//Returns Set data
console.log("The List of Set values:");
console.log(studentEntries);

输出:

迭代集数据

我们可以使用'for … of '循环遍历设置值或条目。以下示例有助于更清楚地理解它。

let diceEntries = new Set();

diceEntries.add(1).add(2).add(3).add(4).add(5).add(6);
 
//Iterate over set entries
console.log("Dice Entries are:"); 
for (let diceNumber of diceEntries) {
    console.log(diceNumber); 
}
 
// Iterate set entries with forEach
console.log("Dice Entries with forEach are:"); 
diceEntries.forEach(function(value) {
  console.log(value);   
});

输出: