JS array, and the use of timer and delayer

preface

On 04day of training 1, I mainly learned the array in JS and the use of timer and delayer.

Tip: the following is the main content of this article. The following cases can be used for reference

DAY04

1, Tab tab Toggle

The same location displays different contents on the interaction of different elements;

Core problem: note that in the for loop, the value of the loop variable i is passed across functions: you need to add an attribute (such as index attribute) to the traversed object to receive the value of the loop variable, and then in its sub function, through this Index to get the value of the corresponding i.

		var liArr = document.getElementsByTagName('li');
		var contentArr = document.getElementsByClassName('content');

		for(var i=0;i<liArr.length;i++){
			liArr[i].a = i;		//An attribute a is added to receive the value of the loop variable i
			liArr[i].onmouseover = function(){
				for(var j=0;j<liArr.length;j++){
					contentArr[j].style.display = "none";
				}
				contentArr[this.a].style.display = "block";		//Obtain the value of the corresponding i through the attribute a added to the object
			}
		}

2, Timer and delay

The so-called timer or delay device is essentially a method;

1. Timer: setInterval() method

(1) Two parameters:

The first parameter: it can usually be a function name or an anonymous function;

Second parameter: clock cycle, in milliseconds; 1s = 1000ms

(2) When used, it is usually received through a variable;

(3) Clear timer: clearInterval()

The method needs a parameter, which is the timer itself;

(4) The functions in the timer method will be executed repeatedly.

2. Delayer: setTimeout() method

The parameters are the same as the timer;

When using, you do not need to use variables to receive, because it can only be executed once; When it needs to be cleared, variables will be used to receive;

Clear delayer: clearTimeout()

​ for(var i=0;i<30;i++){

​ setTimeout(function(){},i*300)

​ }

The delayer method is executed only once.

Note: in the industry, it is recommended to clear the timer or delay device after use;

3, Arrays in JS

1. Concept of array

A collection of variables in the specified order.

The order is determined by the subscript, which starts from 0.

2. Array usage

Arrays are usually used in conjunction with the for loop structure.

3. How arrays are declared

(1) Literal mode

​ var arr = [val1,val2,val3,...]

(2) Use JS built-in object Array()

​ var arr = new Array(4);

Problems needing attention:

Declaration of variable array:

​ var arr = [ ]

​ var arr = new Array()

4. Access to array elements

Through the array variable name, combined with square brackets, write the subscript value of the corresponding element in the square brackets.

For example, arr[3] the fourth element is accessed at this time;

Add: for objects, you can usually use array access to obtain the value of object attribute members.

4, Common methods of array

1. Add element

(1) Add push() from the tail

Syntax: arrays.push(Data you want to add)
          	Directly change the original array
          	The added data is placed at the end of the array
      		Return value: the length of the array after adding
      		
  var arr = [1, 2, 3, 4, 5] //Sample array
  var res = arr.push(6)
  
  console.log(arr)  Print results: [1, 2, 3, 4, 5, 6] //Directly change the original array
  console.log(res)  Print result: 6 //Length of array after adding

(2) Add unshift() from head

Syntax: arrays.unshift(Data you want to add)
          	Directly change the original array
          	Add to the front of the array
          	Return value: the length of the changed array
          
  var arr = [1, 2, 3, 4, 5] //Sample array
  var res = arr.unshift('hello')
  
  console.log(arr)  Print results: ["hello", 1, 2, 3, 4, 5] //Directly change the original array
  console.log(res)  Print result: 6 //Length of array after change

2. Delete element

(1) Remove pop() from the tail

Syntax: arrays.pop()
           	Directly change the original array
           	Deletes the last in the array
         	Return value: the deleted data
         	
  var arr = [1, 2, 3, 4, 5] //Sample array
  var res = arr.pop()
  
  console.log(arr)  Print results: [1, 2, 3, 4] //Directly change the original array
  console.log(res)  Print result: 5 //The deleted data

(2) Remove shift() from head

 Syntax: arrays.shift()
          	Directly change the original array
          	Delete the 0th data in the array
          	Return value: the deleted data
          
  var arr = [1, 2, 3, 4, 5] //Sample array
  var res = arr.shift()
  
  console.log(arr)  Print results: [2, 3, 4, 5] //Directly change the original array
  console.log(res)  Print result: 1 //The deleted data

3. Interception of array

Syntax 1: array.splice(How many indexes are intercepted at the beginning of the index)
          	Directly change the original array
          	Return value: returns the intercepted content in the form of an array
          			(No matter how many contents are intercepted, they are returned in the form of array)
          
  var arr = ['hello', 'world', 'Hello', 'world']
  var res = arr.splice(1, 1)
  
  console.log(arr)  Print results: ["hello", "Hello", "world"] //Directly change the original array
  console.log(res)  Print results: ["world"] //Intercepted content
  
  
 Syntax 2: array.splice(Only one parameter is passed)
 			When the second parameter is not passed, it is intercepted from which index to the end of the array
          	Directly change the original array
          	Return value: returns the intercepted content in the form of an array
          			(No matter how many contents are intercepted, they are returned in the form of array)
          
  var arr = ['hello', 'world', 'Hello', 'world']
  var res = arr.splice(2)
  
  console.log(arr)  Print results: ['hello', 'world'] //Directly change the original array
  console.log(res)  Print results: ['Hello', 'world'] //Intercepted content
    
    
 Syntax 3: array.splice(Starting index, how many indexes are intercepted, value 1, value 2)
 			Starting from the third parameter, the intercepted position is replaced
          	Directly change the original array
          	Return value: returns the intercepted content in the form of an array
          			(No matter how many contents are intercepted, they are returned in the form of array)
  var arr = ['hello', 'world', 'Hello', 'world']
  var res = arr.splice(2,1,'New value 1','New value 2')
  
  console.log(arr)  Print results: ["hello", "world", "New value 1", "New value 2", "world"] //Directly change the original array
  console.log(res)  Print results: ['Hello'] //Intercepted content

4. Sort

Syntax 1: array.sort()
 			Sorting is done one by one (the first number of the first data first, and so on)
          	Directly change the original array
          	Return value: sorted array
          
  var arr = [1, 3, 7, 9, 101, 5]
  var res = arr.sort()
  
  console.log(arr)  Print results: [1, 101, 3, 5, 7, 9] //Directly change the original array
  console.log(res)  Print results: [1, 101, 3, 5, 7, 9] //Sorted array


 Syntax 2: array.sort() //Common grammar
 			The sorting method is to arrange according to the number size
          	Directly change the original array
          	Return value: sorted array (small in order)-->(large)
          
  var arr = [1, 3, 7, 9, 101, 5]
  var res = arr.sort(function (a, b) {
      return a - b
    })
  
  console.log(arr)  Print results: [1, 3, 5, 7, 9, 101] //Directly change the original array
  console.log(res)  Print results: [1, 3, 5, 7, 9, 101] //Sorted array

5. Flip

Syntax: arrays.reverse()
          	Directly change the original array
          	Return value: array after inversion
          
  var arr = ["you", "good", "Joyous", "Welcome"]
  var res = arr.reverse()
  
  console.log(arr)  Print results: ["Welcome", "Joyous", "good", "you"] //Directly change the original array
  console.log(res)  Print results: ["Welcome", "Joyous", "good", "you"] //Inverted array

6. Link an array into a string

 Syntax: arrays.join(What character is the link in) Parameters can not be written. If they are not written, the , link
          	Do not change the original array
          	Return value: the string linked with the specified character(💢Note: is a string)
          
  var arr = [1, 2, 3, 4]
  var res = arr.join('@-@')
  
  console.log(arr)  Print results: [1, 2, 3, 4] //Do not change the original array
  console.log(res)  Print result: 1@-@2@-@3@-@4 //Linked string

5, Traversal method of array

Reference documents:

​ https://blog.csdn.net/weixin_42733155/article/details/81145334?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163992319216780366545789%2522%252C%2522scm%2522%253A%252220140713.130102334...%2522%257D&request_id=163992319216780366545789&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduend~default-1-81145334.pc_search_mgc_flag&utm_term=%E6%95%B0%E7%BB%84%E9%81%8D%E5%8E%86%E7%9A%84%E6%96%B9%E6%B3%95&spm=1018.2226.3001.4187

1. foreach method

forEach is the simplest and most commonly used array traversal method. It provides a callback function that can be used to process each element of the array. By default, there is no return value.

The so-called callback means that the callback function is executed only after the code before the called function is executed. At this time, this function is the callback function.

	let arr = [1,2,3,4,5]
	let res = 0
	arr.forEach(item=>{
		item>=3?res++:res
	})
	console.log(res)

2. map method

map, literally, is a mapping, that is, the mapping of array elements. It provides a callback function. The parameters are the element in the current loop, the subscript of the element, and the array itself, all of which are optional. By default, an array is returned. Each element of the new array is the return value of the original array element after the callback function is executed.

	let arr = [1,2,3,4,5]
	let res = arr.map((item,index)=>{
		return item*(index+1)
	})
	console.log(arr)
	console.log(res)

3. filter method

Filter, which is a conditional filter for array elements. It provides a callback function. The parameters are the element in the current loop, the subscript of the element, and the array itself, all of which are optional. An array is returned by default. If the return value of the element of the original array is true after the callback function is executed, this element will be put into the returned array.

	let arr = [1,2,3,4,5]
	let res = arr.filter((item,index)=>{
		return item*index >= 3
	})
	console.log(arr)
	console.log(res)

4. some, every methods

The usage of some method is very similar to that of every. It provides a callback function. The parameters are the element in the current loop, the subscript of the element, and the array itself, all of which are optional.

Each element of the array will execute a callback function. When all the return values are true, the every method will return true. As long as one of them is false, the every method will return false. When one is true, the some method returns true. When all are false, the every method returns false.

some and every methods do not change the original array.

5. reduce method

The reduce method has two parameters. The first parameter is a callback function (required) and the second parameter is the initial value (optional). The callback function has four parameters, including the cumulative value of the current cycle, the element of the current cycle (required), the subscript of the element (optional) and the array itself (optional).

The reduce method will make each element of the array execute the callback function once, take the return value of the callback function in the previous loop as the initial value of the next loop, and finally return this result.

If there is no initial value, reduce will take the first element of the array as the initial value at the beginning of the loop, and the second element will start to execute the callback function. The most common and simplest scenario is the accumulation and multiplication of array elements.

6. for... of method

es6 adds the concept of interleaver interface to provide a unified access mechanism for all data structures. This access mechanism is for of.

That is, all data with an interleaver interface can be traversed with for... of. Common include arrays, class arrays, sets, maps, etc. all have an interleaver interface.

	let arr = [1,2,3,4,5]
	for(let value of arr){
		console.log(value)
	}

Supplement:

JS holds that everything is an object;

Function:

​ function Rain(){}

task

Assignment 1:

Check the implementation principle of timer;

Assignment 2:

Simulate a lottery game with arrangement 3; It is required to win the prize within three times;

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .div_winning{
      border: orangered 2px solid;
      display: block;
      width: 200px;
      height: 500px;
      position: relative;
      left: 700px;
      float: left;
      font-family: "Hua Wen Caiyun", "Helvetica Neue", Helvetica, sans-serif;
      font-size: 50px;

      text-align: center;
    }
    .div_winning_h1{
      padding-top: 140px;
    }
    #choujiang {
      position: relative;
      left: 700px;
      top: 200px;
    }
    #choujiang1{
      position: relative;
      left: 700px;
      top: 200px;
    }
    .div0{
      margin: 0px;
      padding: 0px;
    }
    .btn0{
      background-color: brown;
      width: 200px;
      height: 50px;
      display: block;
      border-radius: 50px;
    }
  </style>
</head>
<body>
  <div class="div0">
  <button class="btn0" id="btn0">Draw winning numbers</button>
  </div>
  <h1>The winning number is:
    <span id="winning_number"></span>
  </h1>
  <div class="div_winning"><h1 class="div_winning_h1">Hi</h1></div>
  <div class="div_winning"><h1 class="div_winning_h1">Hi</h1></div>
  <div class="div_winning"><h1 class="div_winning_h1">Hi</h1></div>
  <button id="choujiang"><img id="img1" src="./1.png"></button>
  <button id="choujiang1"><img id="img1" src="./2.png"></button>
  <script>
    var btn0 = document.getElementById('btn0')
    var h1 = document.getElementsByTagName('h1');
    var number = document.getElementById('winning_number');
    var btn = document.getElementById('choujiang');
    var btn1 = document.getElementById('choujiang1');
    var div_winning_h1_Arr = document.getElementsByClassName('div_winning_h1');
    btn1.style.cssText="display:none"
    // console.log(btn)
    number.innerText=winning(10);//Range 0 ~ 9, three digits
    var number_style = "font-family:'Hua Wen Caiyun';font-size:80px;color:#"+color_random()+";";
    number.style.cssText = number_style
    //console.log(number)
    var flag = 1;
    var flag_yes_no = Math.round(Math.random());

    var img1 = document.getElementById('img1');
    
    btn0.onclick = function (){
      location.reload();
    }
    var timer = null;
    btn.onclick = function (){
      flag_yes_no = Math.round(Math.random());
      var img1 = document.getElementById('img1');
      //console.log(img1)
      //console.log(1)
      for(var i = 0;i<3;i++){
        div_winning_h1_Arr[i].innerText ="";
        div_winning_h1_Arr[i].style.cssText = "color:#"+color_random()
      }
        timer = setInterval(function(){
				for(var i = 0;i<3;i++){
        div_winning_h1_Arr[i].innerText = rNum(10);
        div_winning_h1_Arr[i].style.cssText = "color:#"+color_random()
        //console.log(div_winning_h1_Arr[i])
      }
			},40)
      btn.style.cssText="display:none"
      btn1.style.cssText="display:block"
      flag++;
		}
    btn1.onclick = function(){
      clearInterval(timer);
      for(var i = 0;i<3;i++){
        div_winning_h1_Arr[i].innerText ="";
        div_winning_h1_Arr[i].style.cssText = "color:#"+color_random()
      }
      //console.log(flag_yes_no)
      if(flag_yes_no){
        setInterval(function(){
				for(var i = 0;i<3;i++){
        div_winning_h1_Arr[i].innerText = number.innerText;
        div_winning_h1_Arr[i].style.cssText = "color:#"+color_random()
        //console.log(div_winning_h1_Arr[i])
      }
			},40)
      }
      else{
        if(flag>=3){
          setInterval(function(){
				for(var i = 0;i<3;i++){
        div_winning_h1_Arr[i].innerText = number.innerText;
        div_winning_h1_Arr[i].style.cssText = "color:#"+color_random()
        //console.log(div_winning_h1_Arr[i])
      }
			},40)
        }
        else{
          for(var i = 0;i<3;i++){
          div_winning_h1_Arr[i].innerText = rNum(10);
          }
        }
      }
      clearInterval(timer);
      //location.reload();
      btn.style.cssText="display:block"
      btn1.style.cssText="display:none"

    }
    function rNum(scope){
			return Math.floor(Math.random()*scope);
		}
    function winning(scope){
      return ''+Math.floor(Math.random()*scope) 
      + Math.floor(Math.random()*scope)
      + Math.floor(Math.random()*scope);
    }
    function color_random(){
      var r = Math.floor(Math.random()*256);
		  var g = Math.floor(Math.random()*256);
		  var b = Math.floor(Math.random()*256);
      return r.toString(16)+g.toString(16)+b.toString(16);
      // console.log(r.toString(16)+g.toString(16)+b.toString(16))
    }
  </script>
</body>
</html>

Operation 3:

Group 30 students randomly, one group for every 3 people, and divide them into 10 groups. Finally, the grouping results will be displayed, and each group will be displayed in another line;

<!DOCTYPE html>
<html>

<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='main.css'>
    <script src='main.js'></script>
</head>

<body>
    <button id="btn1">grouping</button>
    <button id="btn2">Direct grouping</button>
    <p id="allNum"></p>
    <p id="group"></p>
</body>
<script>
    var btn1 = findEleByID("btn1");
    var btn2 = findEleByID("btn2");
    var allNum = findEleByID("allNum");
    var group = findEleByID("group");

    // An array of 30 people
    var num = [];

    // Add 30 person numbers
    for (var i = 0; i < 30; i++) {
        num.push(i + 1);
    }

    allNum.innerText = "Number of all team members:" + num.join(", ");

    // Group each click
    var i = 1;
    btn1.onclick = function () {
        if (i <= 10) {
            getThreeNum(i);
            i++;
        }
        if (i > 10) {
            allNum.innerText = "Grouping completed";
        }
    }
    // Click directly once to group the results
    btn2.onclick = function () {
        while (i <= 10) {
            getThreeNum(i);
            i++;
        }
        if (i > 10) {
            allNum.innerText = "Grouping completed";
        }
    }

    //Randomly obtain the subscript of the number of three people
    function getThreeNum(n) {
        // Store the obtained three person numbers in tnum
        var tnum = [];

        for (var i = 0; i < 3; i++) {
            index = Math.floor(Math.random() * num.length);
            tnum[i] = num.splice(index, 1);
        }

        group.innerHTML += "The first" + n + "Group:" + tnum.join(", ") + "<br/>";
        allNum.innerText = "Number of all team members:" + num.join(", ");
    }

    // Find the corresponding element by id
    function findEleByID(id) {
        return document.getElementById(id);
    }
</script>

</html>

summary

Training one 04day, keep going!

Reward Code:

Reprint please indicate from Huang Honghe!
If there is anything wrong, please contact 1227300886

Keywords: Javascript Front-end TypeScript html

Added by usvpn on Sat, 25 Dec 2021 08:00:33 +0200