Location>code7788 >text

Front-end quick success—Script

Popularity:916 ℃/2025-04-25 20:08:36

Script

1-Introduce js and function calls

  • function function: There must be a return value, and void will never be written. It either returns undefined or returns the data of return

    function etoak(val1, val2, val3) {
                 try {
                     alert('Where to play on May Day?')
                     /* Add breakpoint */
                     /* debugger */
                     /* Console printing is a function provided by the browser */
                     (val1, val2, val3)
                     /* Control the type of print data Note typeof can only print basic type data types */
                     (typeof val1, typeof val2, typeof val3)
                 } catch (err) {
                     (err)
                 } finally {
                     ('finally')
                 }
             }
  • Calling of functions

    • Call directly

              function test() {
                  ('test~~~~~~~~~~~')
              }
              test()
      
    • Bind button trigger

      //<button >Test 2</button>
              
               const nodeBtn2 = ('test2')
               /* Bind the element node to click the trigger function */
                = function () {
                   ('test2~~~~~~~~~~~~~~~~~~')
               }
    • Triggered with event listener

      //<button >Test 3</button>
              
               const nodeBtn3 = ('#test3')
               /* Note that the second parameter here is called the callback function (callback function)
               Indicates that the click event is fired and this function is called back
               In addition, the first parameter of the event listener is the event, without the on prefix!! */
               ('click', function () {
                   ('test3~~~~~~~~~~~~~~~~~~')
               })
  • Function expressions

            const test4 = function () {
                ('test4~~~~~~~~~')
            }
            test4()
    

    The current common writing method when using function expressions with arrows =>

            const test5 = val => (val)
            test5('etoak')
    
            const test6 = (a, b, c) => a + b + c
            (test6(1, 2, 3))
    
  • About format conversion

    Convert string to number Use the Number() function
     Convert string to boolean using the Boolean() function
     Convert string to object Use the Object() function
     Convert string to array Use the Array() function
     Convert string to function Use the Function() function
     Convert string to date Use the Date() function
     Convert string to regexp using the RegExp() function
  • About assignment

    =: Assignment
     ==: Compare whether the two data are equal. If the types are inconsistent, convert to the same type first and then compare
     ===: Compare whether the two data are equal. If the types are inconsistent, then return false directly
     If the types are the same, compare them
     !==: Compare whether the two data are not equal. If the types are inconsistent, convert to the same type first and then compare
  • Output content directly on the page

    (a + '+' + b + '=' + (a + b) + '<br>')
     //This writing method can directly identify HTML tags
  • Results of various types of operations

    let a = 100, b = 'etoak', c = true, d = null
     (a + '+' + b + '=' + (a + b) + '<br>')
     /* ES6 template string must use backticks `${value to be output}`
     Using template strings can avoid using + for string splicing */
     (`${a}+${b}=${a + b}<br>`)
     (`${a}+${c}=${a + c}<br>`)
     (`${a}+${d}=${a + d}<br>`)
     (`${c}+${b}=${c + b}<br>`)
     (`${d}+${b}=${d + b}<br>`)
     (`${d}+${c}=${d + c}<br>`)
     <---------------------------------------------->
     100+etoak=100etoak
     100+etoak=100etoak
     100+true=101
     100+null=100
     true+etoak=trueetoak
     null+etoak=nulletoak
     null+true=1
  • Scrip implements multiplication table

    let str = ''
    for (let i = 1; i <= 9; i++) {
        for (let j = 1; j <= i; j++) {
            str += `${j}*${i}=${j * i}\t`
        }
        str += '<br>'
    }
    (str)
    

2-Operate DOM

  • Operation DOM: Modify, add or delete the structure, content and style of the web page document.

    <button class="btn">Add a line</button>
     //Button
    
     <table class="tb">
             <tr>
                 <td>Default line</td>
             </tr>
         </table>
        //A mediocre single table
       
         <script>
             /* Get element node */
             const nodeBtn = ('.btn')
             /* Bind the click event to the element node */
              = () => {
                 /* Get the table element node */
                 const nodeTb = ('.tb')
                 /* Create a tr element node This node is saved in memory
                 <tr></tr> */
                 const nodeTr = ('tr')
                 /* Modify the structure of the created tr element node and enter the open and close tag
                 Insert hypertext innerHTML Insert hypertext into open and closed tags (recognize tags)
                 innerText Insert text into the open and closed tag
                 Before modification <tr></tr>
                 After modification <tr><td>Add a new line</td></tr>*/
                  = `<td>A new line</td>`
                 /* Append the assembled tr element to the existing table as a child element, if the child element exists
                 Append to the child element */
                 (nodeTr)
                 /* Set a random number This random number is a random integer of 0 - 255 */
                 let r = (() * 256)
                 let g = (() * 256)
                 let b = (() * 256)
                 /* Use js to set element node styles
                 Element node.style.Style name = style value
                 Style name Must use Small camel Format background-color Must be written as backgroundColor
                 font-size must be written as fontSize */
                  = `rgb(${r},${g},${b})`
             }
         </script>

3-Common string methods

  • How to get the length

    Java:
        String     length()
        Array      length
        List       size()
        Map        size()
        Set        size()
    JS:
        String     length
        Array      length
        Map        size()
        Set        size()
    
  • Common operations on strings

    (`String length is ----->${}`)
             (`Replace e with a----->${('e','a')}`)
             (`Get the index value of the first w from left to right----->${('w')}`)
             (`Get the index value of the last w from left to right----->${('w')}`)
             (`Get the string with the index value 8 ----->${(8)}`)
             /* The following three include Return true Not included Return false */
             (`Does www characters contain ----->${('www')}`)
             (`Does it start with http ----->${('http')}`)
             (`Whether it ends with com---->${('com')}`)
             <---------------------------------------------->
             /*
                 Intercept string
                 substring(start,end) start start index (include) end end index (not included)
                 substr(start,length) start start index (include) length intercept length
                 slice(start,end) start start index (include) end end index (not included)
                 It is exactly the same as substring, but you can use negative values ​​to calculate from right to left
                 If you only write one parameter, the functions will be completely consistent.
             */
             (`Seave the string ----->${(3,6)}`)
             (`Seave the string ----->${(3,6)}`)
             (`Seave the string ----->${(3,6)}`)
             <---------------------------------------------->
             /* Split string Here means that the segmentation starts from . */
             let knife = ('.')
             for(let i = 0; i < ; i++){
                 (`${i}----->${knife[i]}`)
             }
             <---------------------------------------------->
             /* join('connector') Use your own defined connector to concatenate multiple strings */
             (('@'))
             <---------------------------------------------->
             /*
                 Other commonly used string methods
                 toUpperCase() converts a string to uppercase
                 toLowerCase() converts a string to lowercase
                 trim() removes whitespace characters at both ends of strings
             */
             (`Convert string to uppercase ----->${()}`)
             (`Convert string to lowercase ----->${()}`)
             (`Remove whitespace characters at both ends of the string ----->${()}`)
             /* Link string */
             (('!!!!!!'))

4-Array

  • Use the constructor to directly construct an array and common methods

            const arr = new Array(100, true, null, 'etoak')
    
    (arr)
             /* push() Add one or more elements to the end of the array */
             (999)
             /* unshift() Add one or more elements to the beginning of the array */
             (0)
             /* ES5 for in iteration */
             for (let index in arr) {
                 (`${index}----->${arr[index]}`)
             }
             /* pop() deletes the last element of the array */
             ()
             /* shift() deletes the first element of the array */
             ()
             /* ES6 for of iteration value is an alias and can be written at will, which is an element in the array */
             for (let value of arr) {
                 (`${value}`)
             }
             /* splice(index,length,replace)
                 index: Start index
                 length: delete number
                 replace: The replaced element is not necessary. If you do not write it, the element will be deleted directly.
             */
             (0, 2, 777, 888)
             (arr)
  • Use object literals to create arrays directly and commonly used methods

    const arr2 = [1, 2, 3, 4, 5]
    
    /* reverse() reverse() reverse array */
             (())
             /* sort() Sort() Default is sorted by string. If you need to sort by number, you need to pass in a comparison function */
             (((a, b) => a - b))
             /*
                 The following three methods are generally used to filter elements in an array, or to perform secondary processing of elements in an array.
                 These three methods will not affect the original array, and will only create a new array
                     filter() writes an expression internally, and only the expression is consistent will be returned, and the final composition
                     A new array
                     find() is similar to filter(), only returning the first element that meets the requirements
                     map() is very similar to iteration, generally performs secondary processing of elements in an array
                     The biggest difference from iteration is that a new array will be generated without affecting the original array.
                     Generally, the new array length generated by the expression is not used is definitely the same as the original array.
             */
             const arr3 = [1, 2, 3, 4, 5]
             /* filter() */
             const newArr3 = (a => a >= 3)
             /* ES6 forEach Iteration */
             ((a, index) =>
                 (`${index}----->${a}`))
    
             /* find() */
             let val = (a => a > 3)
             (val)
    
             /* map() */
             const newArr4 = (a => a * 2)
             (newArr4)
             /* If you have to use an expression in map(), you will return an array of boolean type */
             const newArr5 = (a => a > 3)
             (newArr5)
             /* Other commonly used methods */
             /* concat() merge array */
             (([5, 6, 7]))
             /* join() Convert an array to a string */
             ((''))
             /* include() determines whether an element is included in the array. Contains true and vice versa */
             ((3))
             /* indexOf() Gets the index of the element. If the element does not exist, return -1 */
             ((3), (999))
             /* reduce() accumulator */
             const arr4 = [1, 2, 3]
             const arr4 = [1, 2, 3]
             /*
                 base: base value The last parameter is the default value
                 curr:Each element of the array
                 First iteration 0 + 1 = 1
                 The result of calculation here is the new reference value. The reference value becomes 1 at this time.
                 Second iteration 1 + 2 = 3
                 The third iteration 3 + 3 = 6
             */
             let value = ((base, curr) => base + curr, 0)
             (value)
             /*
                 Get the prototype array Here you can expand the prototype array yourself
             */
              = '🐷Peppa'
              = () => ('Page is running~~~')
             const arr5 = [1, 2, 3]
             (arr5,)
             ()
  • Assigning variables

    • For basic types, let assignment variables, const assignment constants

    • For complex types

      If the data changes frequently, it is generally recommended to use const, because if you use let, each change will be re-addressed. If you change frequently, there will be too much addressing, causing a certain consumption. Const will divide a memory address range in advance, and then search will only look for this range, and the consumption will be less. Therefore, it is recommended to use const with frequent changes in complex types. Note that const cannot be re-assigned.

5-Object

  • Create an object using object literals (maximum use)

    const person = {
                 /* ES6 new features
                     If the attribute name and attribute value happen to be duplicated, only the attribute name can be written */
                 name,
                 age: 17,
                 hobby: ['Shopping', 'Prank', 'Eat Dessert'],
                 address: {
                     info: 'Liyuegang',
                 },
                 etoak() {
                     /* this: This is a keyword used in multiple occasions If written in a global scope, it means
                     Global variable window, if written in object, it represents the current object, if written in page element
                     Then the node representing this element */
                     (`${}year-old ${} like ${[0]}`)
                 },
             }
  • How to operate this object

    (person);
             /* Get an array of all attribute names */
             ((person));
             /* Get an array of all attribute values ​​*/
             ((person));
             /* Get an array of all name-value pairs */
             ((person));
             /* Get attribute value and call method */
             (, person['name'])
             ([0],person['hobby'][0])
             ()
             /* Delete attributes If the deletion is successful, return true. Otherwise, false Note that the attribute name and value will be deleted */
             (delete )
             /* Add properties */
              = 'female'
             /* person['gender'] = 'female' */
             (person)
             /* Add properties and methods to prototype objects */
              = '🐷Peppa'
              = function(){
                 ('🐷Peppai likes🍔')
             }
  • Using the constructor constructor

    const o = new Object()
              = 'Zhang San'
              = 30
             (o,)
             ()

6-Separation Syntax

  • New ES6 Features Use the separation operator... to separate data

  • Separate strings You can split strings into characters one by one

    let str1 = 'hello'
             let str2 = 'Peppa Pig'
             (str1, str2)
             (...str1, ...str2)
             ([...str1], [...str2])
  • Separate arrays You can split the array into elements one by one

            const arr1 = [1, 2, 3]
            const arr2 = [4, 5, 6]
            (...arr1, ...arr2)
            ([...arr1, ...arr2])
            const arr3 = [1, 2, 3]
            const arr4 = [...arr3]
            (arr3, arr4)
    
            const sum = (a, b, c) => a + b + c
            (sum(...arr1))
    
  • Separate objects You can separate the internal name-value pairs, but be careful that you must be encapsulated twice, otherwise an error will be reported.

    const o1 = {
                 name: 'Zhang San',
                 age: 18,
                 gender: 'Male'
             }
             const o2 = { ...o1, married: true, address: 'Jinan' }
             (o1, o2)

7-Deconstruction Assignment

  • Deconstructing values ​​in arrays from left to right is related to order

            const [a, b, c] = [1, 2, 3]
            (a, b, c)
            const [x, y, z] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
            (x, y, z)
            const [m, n] = [1, , 3, 4]
            (m, n)
    
  • The value in the deconstructed object has nothing to do with the order as long as the attribute name corresponds to it.

    const { name, mypass, gender } = {
                 password:'123',
                 name:'Zhang San',
                 Gender:'Male',
             }
             (name, mypass, gender)
  • Deconstructing functions in objects

    const Vue = {
                 createApp(){
                     ('I'm a fake Vue3 factory function...')
                 },
                 createRouter(){
                     ('I'm a fake Vue3 router...')
                 },
             }
             const { createApp, createRouter } = Vue
             createApp()
             createRouter()
             <------------------>
             //If you do not deconstruct, you can call it directly
             ()
             ()

8-Dynamic Form

  • It's a super_small_one that is somewhat similar to the specific implementation of normal Ajax

  • Overall layout and css style design

    • HTML layout

      <link rel="stylesheet" href="./styles/"><--Outline Style-->
          <div class="container">
               <header class="header">
                   <input placeholder="Please enter your name" autofocus autocomplete="off"
                   type="text">
                  
                   Gender: <input type="radio" name="gender" value="0" checked>Male
                   <input type="radio" name="gender" value="1" >Female
      
                   Address:
                   <select name="address" >
                       <option value="Jinan">Jinan</option>
                       <option value="Qingdao">Qingdao</option>
                       <option value="Texas">Texas</option>
                       <option value="Zibo">Zibo</option>
                       <option value="Jining">Jining</option>
                   </select>
                   <input type="button" value="Submit"
                   onclick="add()">
               </header>
               <main class="main"></main>
           </div>
    • CSS Style

      * {
           margin: 0;
           padding: 0;
           box-sizing: border-box;
       }
      
       html,
       body {
           margin: 0;
           padding: 0;
           font-size: 14px;
           height: 100%;
       }
      
       .container{
           margin:0 auto;
           width:80vw;
           height:100vh;
           box-shadow: 15px 15px 10px silver;
           display: flex;
           flex-direction: column;
           .header{
               height:5vh;
               background-color: silver;
               display: flex;
               justify-content: center;
               align-items: center;
               input{
                   margin:15px;
               }
           }
           .main{
               flex:1;
               background-color: #f5f5f5;
               display: flex;
               justify-content: center;
               align-items: flex-start;
               /* Settings table */
               .tb{
                   margin-top: 100px;
                   width:80%;
                   border-collapse: collapse;
                   text-align: center;
                   th,td{
                       border:solid 1px #ddd;
                   }
                   thead tr th{
                       background-color: coral;
                   }
                   /* The following two sentences are also called adding zebra stripe */
                   /* Get all odd numbers of tr */
                   tr:nth-child(odd){
                       background-color: #ddd;
                   }
                   /* Get all even numbers of tr */
                   tr:nth-child(even){
                       background-color: #ffffff;
                   }
               }
              
           }
       }
  • Introducing outreach js

    <!-- Introduce external independent js files. Pay attention to this tag either introduce or write directly. Don't write both-->
         <script src="./script/"></script>
  • Get data from the js package and display the orange table style.

    const query = () => {
                 let table =
                     `<table class="tb">
                     <head>
                         <tr>
                             <th>Serial number</th>
                             <th>Name</th>
                             <th>Gender</th>
                             <th>Address</th>
                             <!-- Please note that you add comments here. Do not use shortcut keys -->
                             <th>Operation</th>
                         </tr>
                     </head>
                     <tbody>`
    
                 if ( === 200 && ) {
                     const { data } = resp
                     ((user, index) => {
                         table +=
                             `<tr>
                             <td>${index + 1}</td>
                             <td>${}</td>
                             <td>${ ? 'female' : 'male'}</td>
                             <td>${user['address']}</td>
                             <td><span style="cursor:pointer"
                             onclick="remove(${index})">Delete</span></td>
                         </tr>`
                     })
                     table += '</tbody></table>'
                     ('.main').innerHTML = table
                 }
             }
             query()
  • Delete data

    const remove = index => {
                 /* A selectable dialog box pops up. Click OK to execute within if. Click Cancel to execute outside if. */
                 if (confirm('Are you sure to delete this record?')) {
                     /* Delete from the given index Delete a */
                     (index, 1)
                     /* Echo Go back and query again Multiplex Function A */
                     query()
                 }
             }
  • Add data

    const add = () => {
                 /* 1: Get the name */
                 let name = ''
                 name = ('input[type="text"]').()
                 if(!name){
                     alert('Please enter valid content~~~~')
                     Return
                 }
                 /* 2: Get gender The default is '0' */
                 let gender = '0'
                 gender = ('input[type="radio"]:checked').value
            
                 /* 3: Obtain address */
                 let address = ('address').value
            
                 /* 4: Add to array */
                 ({
                     /* Generate a random code of letters and numbers */
                     id:().toString(36).slice(2),
                     name,
                     /* Here we want to convert the '0' or '1' of the string to 0 or 1 of number */
                     gender:+gender,
                     address,
                 })
                 /* 5: Echo */
                 query()
             }

9-Deep and shallow copies

  • Copy with equal sign

    /*
                     For basic types, it must be a deep copy
                     For complex types, it must be a shallow copy
             */
             let count1 = 100
             let count2 = count1
             (count1, count2)
             count2++
             (count1, count2)
    
             const arr1 = [1, 2, 3]
             const arr2 = arr1
             (arr1, arr2)
             (999)
             (arr1, arr2)
  • Copy with...separation operator: only for complex types

    const person1 = {
                 name: 'Walnut',
                 age: 18,
                 hobby: ['Prank', 'Shopping'],
             }
             const person2 = { ...person1 }
             (person1, person2)
              = 'Ganyu'
             ++
             ('study')
             (person1, person2)
    
             const o1 = {
                 name: 'Page',
                 address: {
                     info: 'Jinan',
                 },
             }
             const o2 = ({}, o1)
             (o1, o2)
              = 'George'
              = 'Qingdao'
             (o1, o2)
  • Universal converter

    /* (())
                 Also known as universal converter, this copy method is definitely a deep copy, but because it may be subject to data.
                 Causes effects, so use less */