前端速成之——Script

Script

1-引入js和函数调用

  • function函数:必然存在一个返回值,绝对不会书写 void,要么返回 undefine,要么返回 return 的数据

    script 复制代码
            function etoak(val1, val2, val3) {
                try {
                    alert('五一节去哪里玩?')
                    /* 添加断点 */
                    /* debugger */
                    /* 控制台打印 是浏览器提供的功能 */
                    console.log(val1, val2, val3)
                    /* 控制打印数据的类型 注意 typeof 只能打印基本类型的数据类型 */
                    console.log(typeof val1, typeof val2, typeof val3)
                } catch (err) {
                    console.log(err)
                } finally {
                    console.log('finally')
                }
            }
  • 函数的调用

    • 直接调用

      复制代码
              function test() {
                  console.log('test~~~~~~~~~~~')
              }
              test()
    • 绑定按钮触发

      复制代码
              //<button id="test2">测试2</button>
              
              const nodeBtn2 = document.getElementById('test2')
              /* 给元素节点绑定单击事件 单击激发函数 */
              nodeBtn2.onclick = function () {
                  console.log('test2~~~~~~~~~~~~~')
              }
    • 使用事件监听器触发

      复制代码
              //<button id="test3">测试3</button>
              
              const nodeBtn3 = document.querySelector('#test3')
              /* 注意这里第二个参数被称之为 回调函数(callback function) 
              表示单击事件激发后回过头来调用此函数 
              另外 事件监听器的第一个参数是事件,没有on前缀!! */
              nodeBtn3.addEventListener('click', function () {
                  console.log('test3~~~~~~~~~~~~~')
              })
  • 函数表达式

    复制代码
            const test4 = function () {
                console.log('test4~~~~~~~~~')
            }
            test4()

    函数表达式配合箭头使用时目前的常用写法 =>

    复制代码
            const test5 = val => console.log(val)
            test5('etoak')
    
            const test6 = (a, b, c) => a + b + c
            console.log(test6(1, 2, 3))
  • 关于格式转换

    复制代码
    string 转换为 number 使用 Number() 函数
    string 转换为 boolean 使用 Boolean() 函数
    string 转换为 object 使用 Object() 函数
    string 转换为 array 使用 Array() 函数
    string 转换为 function 使用 Function() 函数
    string 转换为 date 使用 Date() 函数
    string 转换为 regexp 使用 RegExp() 函数
  • 关于赋值

    复制代码
    =:赋值
    ==:比较两个数据是否相等,如果类型不一致,则先转换为相同类型,再比较
    ===:比较两个数据是否相等,如果类型不一致,则直接返回false
    如果类型一致,再进行比较
    !==:比较两个数据是否不相等,如果类型不一致,则先转换为相同类型,再比较
  • 直接在页面输出内容

    复制代码
    document.write(a + '+' + b + '=' + (a + b) + '<br>')
    //这种写法可以直接识别HTML标签
  • 关于各种类型进行运算的结果

    复制代码
    let a = 100, b = 'etoak', c = true, d = null
    document.write(a + '+' + b + '=' + (a + b) + '<br>')
    /* ES6 模板字符串 必须使用 反引号 `${要输出的值}`
    使用模板字符串 可以避免 使用 + 进行字符串的拼接 */
    document.write(`${a}+${b}=${a + b}<br>`)
    document.write(`${a}+${c}=${a + c}<br>`)
    document.write(`${a}+${d}=${a + d}<br>`)
    document.write(`${c}+${b}=${c + b}<br>`)
    document.write(`${d}+${b}=${d + b}<br>`)
    document.write(`${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实现乘法表

    复制代码
    let str = ''
    for (let i = 1; i <= 9; i++) {
        for (let j = 1; j <= i; j++) {
            str += `${j}*${i}=${j * i}\t`
        }
        str += '<br>'
    }
    document.write(str)

2-操作DOM

  • 操作DOM : 网页文档结构、内容和样式进行修改、添加或者删除等操作。

    复制代码
    <button class="btn">添加一行</button>
    //按钮
    
    <table class="tb">
            <tr>
                <td>默认一行</td>
            </tr>
        </table>
       //一个平平无奇的单表
       
        <script>
            /* 获取元素节点 */
            const nodeBtn = document.querySelector('.btn')
            /* 给元素节点绑定单击事件 */
            nodeBtn.onclick = () => {
                /* 获取 table 元素节点 */
                const nodeTb = document.querySelector('.tb')
                /* 创建一个 tr 元素节点 这个节点保存在 内存中  
                <tr></tr> */
                const nodeTr = document.createElement('tr')
                /* 修改已经创建完毕的 tr 元素节点的结构 向开闭合标签中
                插入超文本 innerHTML 向开闭合标签中插入超文本(识别标签)
                innerText 向开闭合标签中插入文本 
                修改前 <tr></tr> 
                修改后 <tr><td>新增一行</td></tr>*/
                nodeTr.innerHTML = `<td>新增一行</td>`
                /* 将组装好的 tr 元素 追加到现有表格中作为子元素,原先如果存在子元素
                则追加到子元素的后面 */
                nodeTb.append(nodeTr)
                /* 设置随机数 这个随机数 是 0 - 255 的随机整数 */
                let r = Math.floor(Math.random() * 256)
                let g = Math.floor(Math.random() * 256)
                let b = Math.floor(Math.random() * 256)
                /* 使用 js 设置元素节点样式  
                元素节点.style.样式名 = 样式值 
                样式名 必须使用 小驼峰 格式 background-color 必须写成 backgroundColor
                font-size 必须写成 fontSize */
                nodeTb.style.backgroundColor = `rgb(${r},${g},${b})`
            }
        </script>

3-常用字符串方法

  • 如何获取长度

    复制代码
    Java:
        String     length()
        Array      length
        List       size()
        Map        size()
        Set        size()
    JS:
        String     length
        Array      length
        Map        size()
        Set        size()
  • 对字符串的常用操作

    复制代码
            console.log(`字符串长度是----->${str.length}`)
            console.log(`将e替换为a----->${str.replace('e','a')}`)
            console.log(`从左往右获取第一个w的索引值----->${str.indexOf('w')}`)
            console.log(`从左往右获取最后一个w的索引值----->${str.lastIndexOf('w')}`)
            console.log(`获取索引值是8的字符串----->${str.charAt(8)}`)
            /* 以下三个包含 返回 true 不包含 返回 false */
            console.log(`是否包含 www 字符 ------>${str.includes('www')}`)
            console.log(`是否以 http 开头----->${str.startsWith('http')}`)
            console.log(`是否以 com 结尾----->${str.endsWith('com')}`)
            <---------------------------------------------->
            /*
                截取字符串 
                substring(start,end)  start 起始索引(包含) end 结束索引(不包含)
                substr(start,length)  start 起始索引(包含) length 截取长度
                slice(start,end)  start 起始索引(包含) end 结束索引(不包含)
                与substring 完全一致 但是可以使用负值 从右往左算
                以上三个 如果只写一个参数则功能完全一致
            */
            console.log(`截取字符串----->${str.substring(3,6)}`)
            console.log(`截取字符串----->${str.substr(3,6)}`)
            console.log(`截取字符串----->${str.slice(3,6)}`)
            <---------------------------------------------->
            /* 分割字符串 这里表示从 . 处开始分割 */
            let knife = str.split('.')
            for(let i = 0; i < knife.length; i++){
                console.log(`${i}----->${knife[i]}`)
            }
            <---------------------------------------------->
            /* join('连接符') 使用自己定义的连接符将 多个字符串连接起来 */
            console.log(knife.join('@'))
            <---------------------------------------------->
            /*  
                其它常用的 字符串方法 
                toUpperCase() 将字符串转换为大写
                toLowerCase() 将字符串转换为小写
                trim() 去除字符串两端的空白字符
            */
            console.log(`将字符串转换为大写----->${str.toUpperCase()}`)
            console.log(`将字符串转换为小写----->${str.toLowerCase()}`)
            console.log(`去除字符串两端的空白字符----->${str.trim()}`)
            /* 链接字符串 */
            console.log(str.concat('!!!!!!'))

4-数组

  • 使用构造器直接构造一个数组以及常用方法

    复制代码
            const arr = new Array(100, true, null, 'etoak')
    
            console.log(arr)
            /* push() 向数组末尾添加一个或多个元素 */
            arr.push(999)
            /* unshift() 向数组开头添加一个或多个元素 */
            arr.unshift(0)
            /* ES5 for in 迭代 */
            for (let index in arr) {
                console.log(`${index}----->${arr[index]}`)
            }
            /* pop() 删除数组最后一个元素 */
            arr.pop()
            /* shift() 删除数组第一个元素 */
            arr.shift()
            /* ES6 for of 迭代 value 是别名 可以随意书写 就是数组中的元素 */
            for (let value of arr) {
                console.log(`${value}`)
            }
            /*  splice(index,length,replace) 
                index:起始索引 
                length:删除个数
                replace:替换的元素 不是必须 如果不写则直接删除了元素
            */
            arr.splice(0, 2, 777, 888)
            console.log(arr)
  • 使用对象字面量直接创建数组以及常用方法

    复制代码
    const arr2 = [1, 2, 3, 4, 5]
    
            /* reverse() 反转数组 */
            console.log(arr2.reverse())
            /* sort() 正序排序 默认是按照字符串排序 如果需要按照数字排序 需要传入一个比较函数 */
            console.log(arr2.sort((a, b) => a - b))
            /* 
                以下三个方法一般用来过滤数组中的元素,或者对数组中的元素进行二次加工
                这三个方法不会影响原数组,只会创建一个新的数组
                    filter() 内部书写一个表达式,只有符合表达式才会返回,最终组成
                    一个新的数组
                    find() 与 filter() 类似,仅仅返回第一个符合要求的元素
                    map() 与迭代非常类似,一般是对数组中的元素进行二次加工
                    与迭代最大的不同是,会生成一个新的数组不影响原数组
                    一般不会使用表达式新生成的数组长度肯定与原数组一致
            */
            const arr3 = [1, 2, 3, 4, 5]
            /* filter() */
            const newArr3 = arr3.filter(a => a >= 3)
            /* ES6 forEach 迭代 */
            newArr3.forEach((a, index) =>
                console.log(`${index}----->${a}`))
    
            /* find() */
            let val = arr3.find(a => a > 3)
            console.log(val)
    
            /* map() */
            const newArr4 = arr3.map(a => a * 2)
            console.log(newArr4)
            /* 如果非要在map()中使用表达式,则返回一个 布尔类型的数组 */
            const newArr5 = arr3.map(a => a > 3)
            console.log(newArr5)
            /* 其它常用的方法 */
            /* concat() 合并数组 */
            console.log(arr3.concat([5, 6, 7]))
            /* join() 将数组转换为字符串 */
            console.log(arr3.join(''))
            /* includes() 判断数组中是否包含某个元素 包含 true 反之false */
            console.log(arr3.includes(3))
            /* indexOf() 获取元素的索引 如果元素不存在,则返回-1 */
            console.log(arr3.indexOf(3), arr3.indexOf(999))
            /* reduce() 累加器  */
            const arr4 = [1, 2, 3]
            const arr4 = [1, 2, 3]
            /* 
                base:基准值 最后一个参数就是基准值的 默认值  
                curr:数组的每个元素
                第一次迭代  0 + 1 = 1
                之后这里计算的结果就是新的基准值 基准值此时变为了 1
                第二次迭代  1 + 2 = 3
                第三次迭代  3 + 3 = 6
            */
            let value = arr4.reduce((base, curr) => base + curr, 0)
            console.log(value)
            /* 
                获取原型数组 这里可以自己扩展原型数组
            */
            Array.prototype.name = '🐷佩奇'
            Array.prototype.run = () => console.log('佩奇在奔跑~~~')
            const arr5 = [1, 2, 3]
            console.log(arr5,arr5.name)
            arr5.run()
  • 对于变量进行赋值操作

    • 对于基本类型来说, let 赋值变量, const 赋值常量

    • 对于复杂类型来说

      复制代码
      如果数据变动频繁,一般推荐使用 const,因为如果使用 let 则 每次变动会重新进行寻址,变动频繁则寻址过多,造成一定的消耗,而const 事先会划分一个内存地址范围,之后寻找只会在这个范围中寻找,消耗反而较少 因此复杂类型变动频繁推荐使用 const 注意 const 不能重新赋值

5-对象

  • 使用对象字面量创建一个对象(使用最多)

    复制代码
            const person = {
                /*  ES6 新特性
                    如果属性名和属性值恰好重名,则仅书写属性名即可 */
                name,
                age: 17,
                hobby: ['逛街', '恶作剧', '吃甜品'],
                address: {
                    info: '璃月港',
                },
                etoak() {
                    /* this: 这是一个关键字 使用在多种场合 如果书写在全局作用域则表示
                    全局变量 window,如果书写在对象中则表示当前对象,如果书写在页面元素中
                    则表示这个元素的节点 */
                    console.log(`${this.age}岁的${this.name}喜欢${this.hobby[0]}`)
                },
            }
  • 对于这个对象的操作方法

    复制代码
            console.log(person);
            /* 获取所有属性名组成的数组 */
            console.log(Object.keys(person));
            /* 获取所有属性值组成的数组 */
            console.log(Object.values(person));
            /* 获取所有名值对组成的数组 */
            console.log(Object.entries(person));
            /* 获取属性值 及 调用方法 */
            console.log(person.name, person['name'])
            console.log(person.hobby[0],person['hobby'][0])
            person.etoak()
            /* 删除属性 如果删除成功返回 true 反之false 注意 属性名和值全部会被删除 */
            console.log(delete person.age)
            /* 添加属性 */
            person.gender = '女'
            /* person['gender'] = '女' */
            console.log(person)
            /* 给原型对象添加属性 和 方法 */
            Object.prototype.myname = '🐷佩奇'
            Object.prototype.etoak = function(){
                console.log('🐷佩奇喜欢🍔')
            }
  • 使用构造器构造器

    复制代码
            const o = new Object()
            o.name = '张三'
            o.age = 30
            console.log(o,o.myname)
            o.etoak()

6-分离语法

  • ES6 新特性 使用 分离运算符 ... 来分离数据

  • 分离字符串 可以将字符串拆成一个一个的字符

    复制代码
            let str1 = 'hello'
            let str2 = '小猪佩奇'
            console.log(str1, str2)
            console.log(...str1, ...str2)
            console.log([...str1], [...str2])
  • 分离数组 可以将数组拆成一个一个的元素

    复制代码
            const arr1 = [1, 2, 3]
            const arr2 = [4, 5, 6]
            console.log(...arr1, ...arr2)
            console.log([...arr1, ...arr2])
            const arr3 = [1, 2, 3]
            const arr4 = [...arr3]
            console.log(arr3, arr4)
    
            const sum = (a, b, c) => a + b + c
            console.log(sum(...arr1))
  • 分离对象 可以将内部的名值对分离出来,但是注意 必须二次封装否则报错

    复制代码
            const o1 = {
                name: '张三',
                age: 18,
                gender: '男'
            }
            const o2 = { ...o1, married: true, address: '济南' }
            console.log(o1, o2)

7-解构赋值

  • 解构数组中的值 从左往右与顺序有关

    复制代码
            const [a, b, c] = [1, 2, 3]
            console.log(a, b, c)
            const [x, y, z] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
            console.log(x, y, z)
            const [m, n] = [1, , 3, 4]
            console.log(m, n)
  • 解构对象中的值 从左往右与顺序无关 只要属性名对应即可

    复制代码
            const { name, mypass, gender } = {
                password:'123',
                name:'张三',
                gender:'男',
            }
            console.log(name, mypass, gender)
  • 解构对象中的函数

    复制代码
            const Vue = {
                createApp(){
                    console.log('我是冒牌的Vue3工厂函数...')
                },
                createRouter(){
                    console.log('我是冒牌的Vue3路由器...')
                },
            }
            const { createApp, createRouter } = Vue
            createApp()
            createRouter()
            <-------分割线------->
            //如果不进行解构,可以直接调用
            Vue.createApp()
            Vue.createRouter()

8-动态表格

  • 算是一个super_small_one的跟正常Ajax的具体实现有点相似的东西

  • 整体的布局以及css样式设计

    • HTML布局

      复制代码
         <link rel="stylesheet" href="./styles/main.css"><--外联样式-->
         <div class="container">
              <header class="header">
                  <input placeholder="请输入姓名" autofocus autocomplete="off"
                  type="text">
                  
                  性别: <input type="radio" name="gender" value="0" checked>男
                  <input type="radio" name="gender" value="1" >女
      
                  住址: 
                  <select name="address" id="address">
                      <option value="济南">济南</option>
                      <option value="青岛">青岛</option>
                      <option value="德州">德州</option>
                      <option value="淄博">淄博</option>
                      <option value="济宁">济宁</option>
                  </select>
                  <input type="button" value="提交"
                  onclick="add()">
              </header>
              <main class="main"></main>
          </div>
    • CSS样式

      复制代码
      * {
          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;
              /* 设置表格 */
              .tb{
                  margin-top: 100px;
                  width:80%;
                  border-collapse: collapse;
                  text-align: center;
                  th,td{
                      border:solid 1px #ddd;
                  }
                  thead tr th{
                      background-color: coral;
                  }
                  /* 以下两句又被称之为添加 斑马纹(stripe) */
                  /* 获取所有奇数个的tr */
                  tr:nth-child(odd){
                      background-color: #ddd;
                  }
                  /* 获取所有偶数个tr */
                  tr:nth-child(even){
                      background-color: #ffffff;
                  }
              }
              
          }
      }
  • 引入外联的js

    复制代码
        <!-- 引入外部独立的js文件 注意这个标签 要么引入 要么直接书写 切忌 两者均书写-->
        <script src="./script/response.js"></script>
  • 从js包里面获取数据,并且展示橙表格样式.

    复制代码
            const query = () => {
                let table =
                    `<table class="tb">
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th>姓名</th>
                            <th>性别</th>
                            <th>住址</th>
                            <!-- 注意这里添加注释 不要使用快捷键 -->
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>`
    
                if (resp.code === 200 && resp.flag) {
                    const { data } = resp
                    data.forEach((user, index) => {
                        table +=
                            `<tr>
                            <td>${index + 1}</td>
                            <td>${user.name}</td>
                            <td>${user.gender ? '女' : '男'}</td>
                            <td>${user['address']}</td>
                            <td><span style="cursor:pointer"
                            onclick="remove(${index})">删除</span></td>
                        </tr>`
                    })
                    table += '</tbody></table>'
                    document.querySelector('.main').innerHTML = table
                }
            }
            query()
  • 删除数据

    复制代码
            const remove = index => {
                /* 弹出一个可选择式对话框 点击确定执行if以内 点击取消执行if以外 */
                if (confirm('您确定删除本条记录吗?')) {
                    /* 从给定的索引处删除 删除一个 */
                    resp.data.splice(index, 1)
                    /* 回显 回过头来重新查询一遍 复用 函数A */
                    query()
                }
            }
  • 添加数据

    复制代码
            const add = () => {
                /* 1:获取姓名 */
                let name = ''
                name = document.querySelector('input[type="text"]').value.trim()
                if(!name){
                    alert('请输入有效内容~~~~')
                    return
                }
                /* 2:获取性别 默认是 '0' */
                let gender = '0' 
                gender = document.querySelector('input[type="radio"]:checked').value
            
                /* 3:获取住址 */
                let address = document.getElementById('address').value
            
                /* 4:添加进数组 */
                resp.data.push({
                    /* 生成一个 字母和数字的随机码 */
                    id:Math.random().toString(36).slice(2),
                    name,
                    /* 这里要将 字符串的 '0' 或 '1' 转换为 number 的 0 或 1 */
                    gender:+gender,
                    address,
                })
                /* 5:回显 */
                query()
            }

9-深拷贝和浅拷贝

  • 使用等号拷贝

    复制代码
            /* 
                    对于基本类型 肯定是深拷贝
                    对于复杂类型 肯定是浅拷贝
            */
            let count1 = 100
            let count2 = count1
            console.log(count1, count2)
            count2++
            console.log(count1, count2)
    
            const arr1 = [1, 2, 3]
            const arr2 = arr1
            console.log(arr1, arr2)
            arr2.push(999)
            console.log(arr1, arr2)
  • 使用...分离运算符进行拷贝:只适用于复杂类型

    复制代码
            const person1 = {
                name: '胡桃',
                age: 18,
                hobby: ['恶作剧', '逛街'],
            }
            const person2 = { ...person1 }
            console.log(person1, person2)
            person2.name = '甘雨'
            person2.age++
            person2.hobby.push('学习')
            console.log(person1, person2)
    
            const o1 = {
                name: '佩奇',
                address: {
                    info: '济南',
                },
            }
            const o2 = Object.assign({}, o1)
            console.log(o1, o2)
            o1.name = '乔治'
            o1.address.info = '青岛'
            console.log(o1, o2)
  • 万能转换器

    复制代码
            /*	JSON.stringify(JSON.parse()) 
                又被称之为 万能转换器 这种拷贝方式肯定是 深拷贝,但是由于可能会对数据
                造成影响,因此使用较少 */
相关推荐
YuCaiH14 分钟前
数组理论基础
笔记·leetcode·c·数组
拉不动的猪18 分钟前
前端自做埋点,我们应该要注意的几个问题
前端·javascript·面试
王景程28 分钟前
如何测试短信接口
java·服务器·前端
安冬的码畜日常1 小时前
【AI 加持下的 Python 编程实战 2_10】DIY 拓展:从扫雷小游戏开发再探问题分解与 AI 代码调试能力(中)
开发语言·前端·人工智能·ai·扫雷游戏·ai辅助编程·辅助编程
小杨升级打怪中1 小时前
前端面经-JS篇(三)--事件、性能优化、防抖与节流
前端·javascript·xss
清风细雨_林木木1 小时前
Vue开发网站会有“#”原因是前端路由使用了 Hash 模式
前端·vue.js·哈希算法
bicijinlian1 小时前
多语言笔记系列:使用导入魔法命令
笔记
鸿蒙布道师1 小时前
OpenAI为何觊觎Chrome?AI时代浏览器争夺战背后的深层逻辑
前端·人工智能·chrome·深度学习·opencv·自然语言处理·chatgpt
袈裟和尚1 小时前
如何在安卓平板上下载安装Google Chrome【轻松安装】
前端·chrome·电脑
曹牧2 小时前
HTML字符实体和转义字符串
前端·html