68 lines
1.6 KiB
HTML
68 lines
1.6 KiB
HTML
<html>
|
|
<head>
|
|
<title>Sets (Collections)</title>
|
|
<script language="JavaScript" type="text/JavaScript">
|
|
// create a Set type
|
|
var set1 = new Set();
|
|
|
|
// add 2 values to the set
|
|
set1.add("apple");
|
|
set1.add("oranges");
|
|
|
|
// return the number of members in the set
|
|
console.log(set1.size); // 2
|
|
|
|
// add a new member and then try to add it again
|
|
set1.add("banana");
|
|
set1.add("banana"); // ignored
|
|
|
|
// get the set size again
|
|
console.log(set1.size); // 3
|
|
|
|
// remove (delete) a member
|
|
set1.delete("banana");
|
|
|
|
// get the size again
|
|
console.log(set1.size); // 2
|
|
|
|
// determine if particular values are members or not
|
|
console.log(set1.has("banana")); // false
|
|
console.log(set1.has("apple")); // true
|
|
|
|
// the forEach() method calls a provided function once for each element in a set, in order.
|
|
// using anonymous function
|
|
set1.forEach(function(value) {
|
|
console.log(value);
|
|
});
|
|
|
|
// using a declared function
|
|
set1.forEach(loopFor);
|
|
|
|
function loopFor(value) {
|
|
console.log(value);
|
|
}
|
|
|
|
// convert the set to an array
|
|
var arr = [...set1]; // spread syntax
|
|
console.log(arr[1]); // oranges
|
|
|
|
// create a new set from an array literal
|
|
var set2 = new Set(['one','two','three']);
|
|
|
|
// get the size of the new set
|
|
console.log(set2.size); // 3
|
|
|
|
// same as above but with an array variable
|
|
var arr2 = ['test','again'];
|
|
var set3 = new Set(arr2);
|
|
console.log(set3.size); // 2
|
|
|
|
// remove all members from the set
|
|
set1.clear();
|
|
console.log(set1.size); // 0
|
|
</script>
|
|
</head>
|
|
<body>
|
|
|
|
</body>
|
|
</html> |