es6 series of tutorials - Set Detailed Explanation and Application of Draw Program

Keywords: Javascript Attribute IE

We are still starting from some existing needs and problems. Why is there a set? What problems does it exist to solve?

Let's look at an example of adding key-value pairs to an object

1 var obj = Object.create( null );
2 obj[5] = 'ghostwu'; 
3 console.log( obj["5"] ); //ghostwu
4 console.log( obj[5] ); //ghostwu

With null as the prototype object, create an object and add a numeric key 5 to the object. When output, the numeric key 5 will be automatically converted to the character key "5", which will cause many implicit problems.

1 var obj = Object.create( null );
2 var key1 = {};
3 var key2 = {};
4 obj[key1] = "ghostwu";
5 console.log( obj[key1] ); //ghostwu
6 console.log( obj[key2] ); //ghostwu

In the above program, empty objects are converted to the corresponding string'[object Object]'when they are keys, so obj[key1] and obj[key2] point to the same reference.

obj = {
    num : 0
}
if ( obj.num ) {
    alert( 'Existence of this variable' );
}

Judging whether an object has an attribute, if num is a non-false value, there is no problem above. Now num is 0, the object has a num value, but when judging by if, the result is wrong.

The set set set set of es6 does not produce key variable type conversion.

The basic usage of set:

set is an ordered list with independent, non-repetitive values.

Call new Set() to create a Set collection. If you need to add a value to the set set set, use the add method and the size attribute to get the number of elements in the set.

1 var set = new Set();
2 set.add( 5 );
3 set.add( '5' );
4 console.log( set.size ); //2

5 and'5'are two different values

1 var set = new Set();
2 var key1 = {};
3 var key2 = {};
4 set.add( key1 );
5 set.add( key2 );
6 console.log( set.size ); //2

key1 and key2 are two separate values, although they are empty objects.

Adding a value operation with the same name will be ignored

1 var set = new Set();
2 set.add( 5 );
3 set.add( '5' );
4 set.add( 5 ); //ignore
5 console.log( set.size ); //2

Because the set set set values are non-repetitive

has(): Checks if a value exists in the set set set:

1 var set = new Set();
2 set.add( 5 );
3 set.add( '5' );
4 console.log( set.has( '5' ) ); //true
5 console.log( set.has( 5 ) ); //true
6 console.log( set.has( 'wu' ) ); //false

delete: delete a value, clear: empty set

 1 var set = new Set();
 2 set.add( 5 );
 3 set.add( '5' );
 4 
 5 console.log( set.has( '5' ) ); //true
 6 set.delete( '5' );
 7 console.log( set.has( '5' ) ); //false
 8 
 9 console.log( set.has( 5 ) ); // true
10 console.log( set.size ); // 1
11 
12 set.clear();
13 console.log( set.has( 5 ) ); // false
14 console.log( set.size ); // 0

Using the properties of set, arrays can be repeated

1 var set = new Set( [ 10, 20, 30, 10, 10, 20, 40 ] );
2 console.log( set.size ); //4

Set, like arrays, supports the forEach method, as well as parameters.

1 var set = new Set( [ 'ghostwu', 'name of a fictitious monkey with supernatural powers', 'Eight quit' ] );
2 set.forEach( function( val, key, cur ){
3     console.log( key, val, cur );
4 } );

Keys are the same as values. The key of an array is a digital index, which is different. So Sets can't take values like array indexes, but we can convert Sets into arrays, and we can make use of the non-repetitive nature of sets to repeat arrays.

1 var set = new Set( [ 10, 20, 30, 10, 10, 20, 40 ] );
2 var arr = [...set];
3 console.log( arr ); // 10, 20, 30, 40

Encapsulated as a function of de-duplication

1 function unique( arr ){
2     return [...new Set( arr )];
3 }
4 var arr = [ 'abc', 'ghostwu', 'abc', 'ghostwu' ];
5 console.log( unique( arr ) ); //abc, ghostwu

 

Apply the set feature to make a multi-person lottery program to make sure that everyone wins the only prize.

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 7     <title>Document</title>
 8     <style>
 9         #box {
10             width: 300px;
11             height: 100px;
12             line-height: 100px;
13             font-size: 30px;
14             text-align: center;
15             border: 1px solid #aaa;
16             box-shadow: 2px 2px 3px #ccc;
17         }
18     </style>
19 </head>
20 <body>
21     <div id="box"></div>
22     <input type="button" value="Xiao Ming">
23     <input type="button" value="Small B">
24     <input type="button" value="Small A">
25     <input type="button" value="Little new">
26     <input type="button" value="Leaflet">
27     <script>
28         var aPrize = ['millet', 'iphone5', 'iphone6', 'iphone7', 'iphone8'],
29             aInput = document.querySelectorAll("input"),
30             oBox = document.querySelector("#box"),
31             set = new Set(), rand = null;
32         aInput.forEach((ele, ind, cur) => {
33             ele.flag = false;
34             ele.addEventListener('click', () => {
35                 if ( !ele.flag ) {
36                     rand = Math.floor(Math.random() * aPrize.length);
37                     if (!set.has(rand)) {
38                         set.add(rand);
39                     } else {
40                         while (set.has(rand)) {
41                             rand = Math.floor(Math.random() * aPrize.length);
42                             if (!set.has(rand)) {
43                                 set.add(rand);
44                                 break;
45                             }
46                         }
47                     }
48                     oBox.innerHTML = aPrize[rand];
49                     ele.flag = true;
50                     ele.value = 'You've already smoked.';
51                 }
52             }, ele);
53         });
54     </script>
55 </body>
56 </html>

Posted by tinyashcities on Wed, 22 May 2019 13:22:55 -0700