ES6基礎與解構賦值(高顏值彈框小案例!)

来源:https://www.cnblogs.com/chenyingying0/archive/2020/01/05/12153676.html
-Advertisement-
Play Games

let只作用在當前塊級作用域內使用let或者const聲明的變數,不能再被重新聲明let不存在`變數提升` console.log(dad); var dad = '我是爸爸!';//預定義undefined console.log(dad); let dad = '我是爸爸!';//報錯 生成十個 ...


let只作用在當前塊級作用域內
使用let或者const聲明的變數,不能再被重新聲明
let不存在`變數提升`

    console.log(dad);
    var dad = '我是爸爸!';//預定義undefined

    console.log(dad);
    let dad = '我是爸爸!';//報錯

生成十個按鈕 每個按點擊的時候彈出1 - 10
var 方法:

    var i = 0;
    for (i = 1; i <= 10; i ++) {
      (function(i) {
        var btn = document.createElement('button');
        btn.innerText = i;
        btn.onclick = function() {
          alert(i)
        };
        document.body.appendChild(btn);
      })(i);
    }

let方法:

    for (let i = 1; i <= 10; i ++) {
      var btn = document.createElement('button');
      btn.innerText = i;
      btn.onclick = function() {
        alert(i)
      };
      document.body.appendChild(btn);
    }

ES6之前的作用域:全局作用域、函數作用域、eval作用域、ES6塊級作用域


 

常量聲明後不能被修改

  const NAME = '小明';
  NAME = '小紅';//報錯

q: 怎麼防止常量為引用類型的時候能被修改的情況
Object.freeze()

    const xiaoming = {
      age: 14,
      name: '小明'
    };
    Object.freeze(xiaoming);
    console.log(xiaoming);
    xiaoming.age = 22;
    xiaoming.dd = 11;
    console.log(xiaoming);

    const ARR = [];
    Object.freeze(ARR);
    ARR.push(1);
    console.log(ARR);

Object的hasOwnProperty()方法返回一個布爾值,判斷對象是否包含特定的自身(非繼承)屬性

    var obj1 = {
        a: 1,
        b: 2
    }

    var obj2 = Object.create(obj1);

    obj2.c = 3;
    obj2.d = 4;

    for (let i in obj2) {
        if (obj2.hasOwnProperty(i)) {
            document.body.innerHTML += (i + ': ' + obj2[i] + '<br>');
        }
    }

數組的解構賦值

    const arr = [1, 2, 3, 4];
    let [a, b, c, d] = arr;
    console.log(a);

更複雜的匹配規則

    const arr = ['a', 'b', ['c', 'd', ['e', 'f', 'g']]];
    const [ , b] = arr;
    const [ , , g] = ['e', 'f', 'g']
    const [ , , [ , , g]] = ['c', 'd', ['e', 'f', 'g']];
    const [ , , [ , , [ , , g]]] = arr;

擴展運算符  ...

    const arr1 = [1, 2, 3];
    const arr2 = ['a', 'b'];
    const arr3 = ['zz', 1];
    const arr4 = [...arr1, ...arr2, ...arr3];
    const arr = [1, 2, 3, 4, 5, 6];
    const [a, b, ...c] = arr;

預設值

    const arr = [1, null, undefined];
    const [a, b = 2, c, d = 'aaa'] = arr;

交換變數

    [a, b] = [b, a];

接收多個函數返回值

    function getUserInfo(id) {
      // .. ajax
      return [
        true,
        {
          name: '小明',
          gender: '女',
          id: id
        },
        '請求成功'
      ];
    };
    const [status, data, msg] = getUserInfo(123);

對象的解構賦值

    const obj = {
        saber: '阿爾托利亞',
        archer: '衛宮'
    };
    const { saber, archer1 } = obj;

稍微複雜的解構條件

    const player = {
        nickname: '感情的戲∫我沒演技∆',
        master: '東海龍王',
        skill: [{
            skillName: '龍吟',
            mp: '100',
            time: 6000
        },{
            skillName: '龍卷雨擊',
            mp: '400',
            time: 3000
        },{
            skillName: '龍騰',
            mp: '900',
            time: 60000
        }]
    };

    const { nickname } = player;
    const { master } = player;
    const { skill: [ skill1, { skillName }, { skillName: sklName } ] } = player;
    const { skill } = player;
    const [ skill1 ] = skill;

結合擴展運算符

    const obj = {
        saber: '阿爾托利亞',
        archer: '衛宮',
        lancer: '瑟坦達'
    };
    const { saber, ...oth } = obj;

對已經申明瞭的變數進行對象的解構賦值

    let age;
    const obj = {
        name: '小明',
        age: 22
    };
    ({ age } = obj);

預設值

    let girlfriend = {
        name: '小紅',
        age: undefined,
    };
    let { name, age = 24, hobby = ['學習'] } = girlfriend;

字元串的結構賦值

    const str = 'I am the bone of my sword'; // 我是劍骨頭
    const [ a, b ,c, ...oth ] = str;
    const [ ...spStr1 ] = str;

提取屬性

    const { length, split } = str;

數值與布爾值的解構賦值

    const { valueOf: vo } = 1;
    const { toString: ts } = false;

函數參數的解構賦值

    function swap([x, y]) {
        return [y, x];
    };

    let arr = [1, 2];
    arr = swap(arr);
    function Computer({
        cpu,
        memory,
        software = ['ie6'],
        OS = 'windows 3.5'
    }) {

        console.log(cpu);
        console.log(memory);
        console.log(software);
        console.log(OS);

    };

    new Computer({
        memory: '128G',
        cpu: '80286',
        OS: 'windows 10'
    });

最後來一個高顏值彈框小案例~

按照國際慣例先放圖

index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
      <link rel="stylesheet" href="./msg.css">
    </head>
    <body>
      <button>彈個框</button>
      <div id="t"></div>
      <script src="./msg.js"></script>
      <script>
        document.querySelector('button').addEventListener('click', function() {
          new $Msg({
            content: '真的要刪除嗎...',
            title: '確認刪除',
            type: 'wrong',
            btnName: ['好的', '算了吧'],
            confirm: function(e) {
              console.log(this);
              console.log(e);
              new $Msg({
                content: '刪除成功<span style="color: red">~</span>',
                type: 'success',
                footer: false,
                useHTML: true,
                header: false
              })
            },
            cancel: function(e) {
              document.querySelector('#t').innerHTML += '取消了,';
            }
          });
        });
      </script>
    </body>
    </html>

msg.css

    /* 彈出框最外層 */
    .msg__wrap {
      position: fixed;
      top: 50%;
      left: 50%;
      z-index: 10;
      transition: all .3s;
      transform: translate(-50%, -50%) scale(0, 0);
      max-width: 50%;
      
      background: #fff;
      box-shadow: 0 0 10px #eee;
      font-size: 10px;
    }

    /* 彈出框頭部 */
    .msg__wrap .msg-header {
      padding: 10px 10px 0 10px;
      font-size: 1.8em;
    }

    .msg__wrap .msg-header .msg-header-close-button {
      float: right;
      cursor: pointer;
    }

    /* 彈出框中部 */
    .msg__wrap .msg-body {
      padding: 10px 10px 10px 10px;
      display: flex;
    }

    /* 圖標 */
    .msg__wrap .msg-body .msg-body-icon{
      width: 80px;
    }

    .msg__wrap .msg-body .msg-body-icon div{
      width: 45px;
      height: 45px;
      margin: 0 auto;
      line-height: 45px;
      color: #fff;
      border-radius: 50% 50%;
      font-size: 2em;
    }

    .msg__wrap .msg-body .msg-body-icon .msg-body-icon-success{
      background: #32a323;
      text-align: center;
    }

    .msg__wrap .msg-body .msg-body-icon .msg-body-icon-success::after{
      content: "成";
    }

    .msg__wrap .msg-body .msg-body-icon .msg-body-icon-wrong{
      background: #ff8080;
      text-align: center;
    }

    .msg__wrap .msg-body .msg-body-icon .msg-body-icon-wrong::after{
      content: "誤";
    }

    .msg__wrap .msg-body .msg-body-icon .msg-body-icon-info{
      background: #80b7ff;
      text-align: center;
    }

    .msg__wrap .msg-body .msg-body-icon .msg-body-icon-info::after{
      content: "註";
    }

    /* 內容 */
    .msg__wrap .msg-body .msg-body-content{
      min-width: 200px;
      font-size: 1.5em;
      word-break: break-all;
      display: flex;
      align-items: center;
      padding-left: 10px;
      box-sizing: border-box;
    }

    /* 彈出框底部 */
    .msg__wrap .msg-footer {
      padding: 0 10px 10px 10px;
      display: flex;
      flex-direction: row-reverse;
    }

    .msg__wrap .msg-footer .msg-footer-btn {
      width: 50px;
      height: 30px;
      border: 0 none;
      color: #fff;
      outline: none;
      font-size: 1em;
      border-radius: 2px;
      margin-left: 5px;
      cursor: pointer;
    }

    .msg__wrap .msg-footer .msg-footer-cancel-button{
      background-color: #ff3b3b;
    }

    .msg__wrap .msg-footer .msg-footer-cancel-button:active{
      background-color: #ff6f6f;
    }

    .msg__wrap .msg-footer .msg-footer-confirm-button{
      background-color: #4896f0;
    }

    .msg__wrap .msg-footer .msg-footer-confirm-button:active{
      background-color: #1d5fac;
    }

    /* 遮罩層 */
    .msg__overlay {
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      z-index: 5;
      background-color: rgba(0, 0, 0, .4);
      transition: all .3s;
      opacity: 0;
    }

msg.js

    (function (window, document) {

      /**
       * 暴露出去的構造函數
       * @param {*} options 
       */
      let Msg = function (options) {
        this._init(options);
      }

      /**
       * 初始化傳入的配置後創建元素 並顯示
       * @param {*} param0 
       */
      Msg.prototype._init = function ({ 
        content = '', 
        type = 'info', 
        useHTML = false, 
        showIcon = true, 
        confirm = null, 
        cancel = null, 
        footer = true,
        header = true,
        title = '提示', 
        contentStyle = {}, 
        contentFontSize = '1.5em', 
        btnName = ['確定', '取消']
      }) {
        this.content = content;
        this.type = type;
        this.useHTML = useHTML;
        this.showIcon = showIcon;
        this.confirm = confirm;
        this.cancel = cancel;
        this.footer = footer;
        this.contentStyle = contentStyle;
        this.contentFontSize = contentFontSize;
        this.title = title;
        this.btnName = btnName;
        this.header = header;

        this._createElement();
        // 給dom上的按鈕們和遮罩層綁定事件
        this._bind({ el: this._el, overlay: this._overlay });
        this._show({ el: this._el, overlay: this._overlay });
      }

      /**
       * 創建彈出框
       */
      Msg.prototype._createElement = function () {

        let wrap = document.createElement('div');
        wrap.className = 'msg__wrap';

        const [ confirmBtnName, cancelBtnName ] = this.btnName;

        // 判斷是否顯示圖標
        const iconHTML = this.showIcon 
          ? '<div class="msg-body-icon">\
              <div class="msg-body-icon-' + this.type + '"></div>\
            </div>' 
          : '';

        // 判斷是否顯示彈出框底部按鈕
        const footerHTML = this.footer 
          ? '<div class="msg-footer">\
              <button class="msg-footer-btn msg-footer-cancel-button">' + cancelBtnName + '</button>\
              <button class="msg-footer-btn msg-footer-confirm-button">' + confirmBtnName + '</button>\
            </div>' : '';

        const headerHTML = this.header
          ? '<div class="msg-header">\
              <span>' + this.title + '</span>\
              <span class="msg-header-close-button">×</span>\
            </div>'
          : '';

        // 拼成完整html
        const innerHTML = headerHTML +
                          '<div class="msg-body">' 
                            + iconHTML + 
                            '<div class="msg-body-content"></div>\
                          </div>'
                          + footerHTML;

        // 將容器內的html替換成彈出框內容
        wrap.innerHTML = innerHTML;

        // 生成合併自定義的內容樣式
        const contentStyle = {
          fontSize: this.contentFontSize,
          ...this.contentStyle
        }

        // 獲取內容dom
        let content = wrap.querySelector('.msg-body .msg-body-content');

        // 給內容容器加上自定義樣式
        for (let key in contentStyle) {
          content.style[key] = contentStyle[key];
        }

        // 給彈出框內容賦值
        if (this.useHTML) {
          content.innerHTML = this.content;
        } else {
          content.innerText = this.content;
        }

        // 創建遮罩層
        let overlay = document.createElement('div');
        overlay.className = 'msg__overlay';

        // 把dom掛到當前實例上
        this._overlay = overlay;
        this._el = wrap;
      }

      /**
       * 顯示彈出框
       * @param {*} param0 
       */
      Msg.prototype._show = function ({ el, overlay }) {

        // 把遮罩和彈出框插到頁面中
        document.body.appendChild(el);
        document.body.appendChild(overlay);

        // 顯示
        setTimeout(function () {
          el.style.transform = 'translate(-50%, -50%) scale(1, 1)';
          overlay.style.opacity = '1';
          console.log(1);
        });
        console.log(2);
      }

      /**
       * 綁定事件
       * @param {*} param0 
       */
      Msg.prototype._bind = function ({ el, overlay }) {
        // 保留this
        const _this = this;

        // 隱藏彈出框
        const hideMsg = function () {
          _this._el.style.transform = 'translate(-50%, -50%) scale(0, 0)';
          _this._overlay.style.opacity = '0';

          setTimeout(function () {
            document.body.removeChild(_this._el);
            document.body.removeChild(_this._overlay);
          }, 300);
        }

        // 取消事件
        const close = function (e) {
          _this.cancel && _this.cancel.call(_this, e);
          hideMsg();
        }

        // 確定事件
        const confirm = function (e) {
          _this.confirm && _this.confirm.call(_this, e);
          hideMsg();
        }

        overlay.addEventListener('click', close);

        if (this.header) {
          el.querySelector('.msg-header .msg-header-close-button').addEventListener('click', close);    
        }

        if (this.footer) {
          el.querySelector('.msg-footer .msg-footer-cancel-button').addEventListener('click', close);
          el.querySelector('.msg-footer .msg-footer-confirm-button').addEventListener('click', confirm);
        }
      }

      // 註冊到全局對象
      window.$Msg = Msg;

    })(window, document);

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 場景 實現效果如下 註: 博客: https://blog.csdn.net/badao_liumang_qizhi 關註公眾號 霸道的程式猿 獲取編程相關電子書、教程推送與免費下載。 實現 將佈局改為相對佈局,然後添加一個Chronometer,並添加id屬性。 <?xml version="1. ...
  • 場景 實現效果如下 註: 博客: https://blog.csdn.net/badao_liumang_qizhi 關註公眾號 霸道的程式猿 獲取編程相關電子書、教程推送與免費下載。 實現 將佈局改為相對佈局,然後添加一個TimePicker,並添加id屬性。 <?xml version="1.0 ...
  • 場景 實現效果如下 註: 博客: https://blog.csdn.net/badao_liumang_qizhi 關註公眾號 霸道的程式猿 獲取編程相關電子書、教程推送與免費下載。 實現 將佈局改為相對佈局,然後添加一個DataPicker,並添加id屬性。 <?xml version="1.0 ...
  • 場景 Android佈局管理器-使用FrameLayout幀佈局管理器顯示層疊的正方形以及前景照片: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103839149 實現效果如下 註: 博客: https://blog.csdn ...
  • 以下內容摘自--ES6標準入門(阮一峰),純粹為了記憶。 函數參數的預設值 1、基本用法 在ES6之前,不能直接為函數的參數指定預設值,只能採用變通的方法。 如果用戶給參數y賦值false,這時候是不起作用的。並且以上第三個y參數期望輸出空串,但是也變為了World.為了避免這種情況我們可以變為以下 ...
  • 模板字元串和標簽模板 const getCourseList = function() { // ajax return { status: true, msg: '獲取成功', data: [{ id: 1, title: 'Vue 入門', date: 'xxxx-01-09' }, { id: ...
  • 模擬命令行的界面效果,使用swoole作為websocket的服務,重新做了下html的界面效果 ...
  • 結構偽類選擇器介紹 結構偽類選擇器是用來處理一些特殊的效果。 結構偽類選擇器屬性說明表 屬性 | 描述 | E:first child | 匹配E元素的第一個子元素。 E:last child | 匹配E元素的最後一個子元素。 E:nth child(n) | 匹配E元素的第n個子元素。 E:nth ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...