大前端 — js es6 中的小技巧

1.關於解構

在數組的解構中,如果我只想要 第三個,怎麼辦?
很簡單,我甚至還能夠給這個設置默認值

const arr = [1, 2, 3, 5, 6, 7, 8]

const [,,third = 'third'] = arr

如果我想要一個對象除了 某一個 字段之外的新對象

const obj = {
  want1: true,
  want2: true,
  want3: true,
  dont: false
}
const {
  dont,
  ... obj2
} = obj;

// 這樣,obj2 就完美地滿足了自己的要求

2.模板字符串

在之前,寫模板語法的時候,是使用 正則表達式 來匹配的,下面來看一下模板方法模式

// 模板語法中的格式化字符串方法
var tpl = {
  formateString: function (str, data) {
    return str.replace(/\{%(\w+)%\}/g, function (match, key) {
      return data[key] ? data[key] : '';
    })
  },
  formateArr: function (str, dataArr) {
    var dom = '';
    var _this = this;
    if (!dataArr) {
      return ''
    }
    dataArr.map(function (data) {
      dom += _this.formateString(str, data);
    })
    return dom;
  }
};
// 模板語法中的 樣式模板
var template = ['<a href="{%href%}"><h2>{%name%}</h2></a>',
                '<div>{%content%}</div>'].join('');
var tempdata = {
   name: '標題',
   content: '內容',
   href: 'https://www.baidu.com'
}

var result = tpl.formateString(template, tempdata);

可以看到,最後 result 的輸出結果就是

<a href="https://www.baidu.com"><h2>標題</h2></a><div>內容</div>

那麼如果加上 es6 中的模板字符串,就可以丟掉 那一大堆的格式化字符串方法了

var temp = (obj) => `<a href="${obj.href}"><h2>${obj.name}</h2></a>''<div>${obj.content}</div>'`

temp({
   name: '標題',
   content: '內容',
   href: 'https://www.baidu.com'
}})

3.對象的比較

Object.is(-0, 0) // false
Object.is(NaN, NaN) // true

4.Proxy  & Reflect 與 Object 對象屬性的比較

5.異步迭代器

看我寫的這一篇 文章

6.字符串

有時候會遇到這樣一個需求,要在 小於 10 的情況下,在前面增加一個 0

// 通常的方法 是 判斷 數字的大小,然後增加,或者轉化爲字符串之後,判斷字符串長度
if (`num`.length === 1) {
  num = `0${num}`
}

但是現在有了更好的方法

num = `${num}`.padStart(2, 0)

對應於padStart, 還存在 padEnd 方法

7.ajax 請求

作爲 面試中的必考題,以前的寫法是這樣的

function Ajax(url, callback) {
  var xhr = new XMLHttpRequest()
  xhr.open('Get', url)
  xhr.onreadystatechange = function() {
     if(xhr.readyStatus === 4 && xhr.status === 200) {
        callback(xhr.responseText)
     }
  }
   xhr.send()
}

但是現在 已經 可以摒棄 readyStaus 的寫法了,轉而使用 onload

​function ajax (url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XHRHttpRequest()
    xhr.open('GET', url)
    xhr.responseType = 'json'
    xhr.onload = function() {
       if (this.status === 200) {
           resolve(this.response)
       } else {
           reject(new Error())
       }
    }
    xhr.send()
  })
}

 

8. 在 vs code 中打開chrome 中的控制檯

 

這個時候高呼 萬萬沒想到!沒想到 vs code 就是一個 瀏覽器!!!!!!

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章