大前端 — 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 就是一个 浏览器!!!!!!

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值