es6语法笔记

const

const修饰对象是可以改的,怎么让这个对象不能改呢,就是

const person = {name:'sdf', age: 12}
const sdfs = Object.freeze(person)

用freeze修饰的对象不能改了

箭头函数

箭头函数有两个参数,第一个参数是value,第二个是index

const numbers = [1,2,3]
const double = numbers.map((value,i) => {console.log(value, i)})

特别说明;箭头函数没有argument
使用默认对象的绑定不要使用箭头函数,因为这个时候this没有绑定到这个对象上面

button.addEventListener('click', () => {console.log(this};this.classList.add('in');)

这里的this就不是button而是window

函数默认值

以前的写法

function(a,b){
a = a||3;
b = b||5;
return a*b
}

es6里面的写法

function(a=3,b=5){
 return a*b;
}

模板字符串

非常方便,可以用来打印对象

 const jelly = {
        name: 'jelly',
        date: '2017-05-07',
        todos:[
            {name: 'go to store1', complete: true},
            {name: 'go to store2', complete: false},
            {name: 'go to store3', complete: false},
        ]
    }
    const template = `
    <ul>
        ${jelly.todos.map(todo => `
            <li>
                ${todo.name} ${todo.complete? '√':'×'}
            </li>`).join('')}
    </ul>
    `
    document.body.innerHTML = template;

也可以用来给函数传变量

 function hightLight(strings, ...values){ 
 			debugger
            return 'larityList'
        }
  const user = 'Mary';
  const topic = 'Learn to use markdown';
  const sentence = hightLight`${user} has commented on your topic ${topic}`;
  console.log(sentence) // larityList

在这里插入图片描述
在这里插入图片描述
这两个变量的值如图所示, 由于模板字符串以变量开头结尾,所以前后有两个空字符串

<!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>
    <style>
        .hightlight{
            padding: 2px 5px;
            background: #00adb5;
            color: white;
        }
    </style>
</head>
<body>
</body>
<script>
    function hightLight(strings, ...values){
        const hightLighted = values.map(value => `<span class = "hightlight">${value}</span>`)
        let str = '';
        strings.forEach((string, i) => str += `${string}${hightLighted[i] || ''}`);
       // return strings.reduce((prev, curr, i) => `${prev}${curr}${hightLighted[i] || ''}`, '') 一句代码解释
        return str
    }
    const user = 'Mary';
    const topic = 'Learn to use markdown';
    const sentence = hightLight`${user} has commented on your topic ${topic}`;
    document.body.innerHTML = sentence;
</script>
</html>

在这里插入图片描述
主要使用场景: 处理用户的输入 ,配合sanitize,过滤脚本攻击

debugger 自定义断点

对象结构

 const Tome = {
        name: 'Tome',
        age: 25,
        family: {
            mother: 'Norah Jones',
            father: 'Richard Jones',
            brother: 'Howard Jones'
        }
    }
    const {name, age} = Tome;
    console.log('name', name)
    console.log('age', age)

这种写法注意前面不能定义name和age
如果定义了就用下面的写法

const Tome = {
        name: 'Tome',
        age: 25,
        family: {
            mother: 'Norah Jones',
            father: 'Richard Jones',
            brother: 'Howard Jones'
        }
    }
    let name = '';
    let {name, age} = Tome;
    console.log('name', name)
    console.log('age', age)

有嵌套的对象也可以

const Tome = {
      name: 'Tome',
       age: 25,
       family: {
           mother: 'Norah Jones',
           father: 'Richard Jones',
           brother: 'Howard Jones'
       }
   }
   let {mother, father, brother} = Tome.family;
   console.log('mother', mother)
   console.log('father', father)
   console.log('brother', brother)

如果对象已经定义了就重命名

const Tome = {
        name: 'Tome',
        age: 25,
        family: {
            mother: 'Norah Jones',
            father: 'Richard Jones',
            brother: 'Howard Jones'
        }
    }
    let mother = ''
    let {mother: m, father, brother} = Tome.family;
    console.log('m', m)
    console.log('father', father)
    console.log('brother', brother)

对象结构的综合使用

<div class="container"></div>
    <script>
        function appendChildDiv(options= {}) {
            const {parent = 'body', width = '100px', height = '80px', backgroundColor = 'pink'} = options;
            const div = document.createElement('div');
            div.style.width = width;
            div.style.height = height;
            div.style.backgroundColor = backgroundColor;

            document.querySelector(parent).appendChild(div);
        }
        appendChildDiv({
            parent: '.container',
            width: '200px',
            height: '150px',
            backgroundColor: 'yellow'
        })
    </script>

注意默认值只有这个值位underfined的时候才能生效,位null或者0都不生效
除了对象,数组也可以这样使用

const numbers = ['one','two','three','four'];
const [one1, two1, three1] = numbers
console.log(one1, two1, three1) // one two three

还可以这样使用,剩下的一组

const [one, ...others] = numbers;
console.log(one) // one
console.log(others) // ["two", "three", "four"]

交换变量值

let aa = 10;
let bb = 20;
[aa, bb] = [bb, aa]
console.log(aa)
console.log(bb)

es6新增for循环

先说说之前几种循环的缺点
普通for循环 难写 难读

const fruits = ['appple','banana', 'orange']
 for (let i = 0; i < fruits.length; i++) {
           console.log(fruits[i])
       }

lambda表达式 不能使用continue和break

   fruits.forEach(fruit => {
         console.log(fruit)
      })

foreach循环 会把原型带进来 而且循环的是下标 还要根据下标去取

const fruits = ['appple','banana', 'orange']
 Array.prototype.first = '423423'
 for (const index in fruits) {
            //判断不是原型的属性
            if (fruits.hasOwnProperty(index)) {
                console.log(fruits[index])
            }
        }

所以es6推出了新的for循环 for of 非常好用

for (const fruit of fruits) {
     if(fruit == 'banana'){
         continue;
     }
     console.log(fruit)
 }

也可以获取键和值

 for (const [index,fruit] of fruits.entries()) {
        if(fruit == 'banana'){
             continue;
         }
         console.log(fruit)
     }

综合使用

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
     .complete{
         text-decoration: line-through;
     }
    </style>
</head>
<body>
    <ul>
        <li>GO to store1</li>
        <li>GO to store2</li>
        <li>GO to store3</li>
    </ul>
    <script>
      const lis = document.querySelectorAll('li');
      for(let li of lis){
          li.addEventListener('click', function(){
              console.log(this.classList)
              this.classList.toggle('complete')
          })
      }
    </script>
</body>

Object.assign()的用法

Object.assign方法用来将源对象(source)的所有可枚举属性,复制到目标对象(target)。它至少需要两个对象作为参数,第一个参数是目标对象,后面的参数都是源对象。

let targetObj1 = { a: 1 };
let sourceObj1 = { b: 1 };
let sourceObj11 = { c: 3 };
Object.assign(targetObj1, sourceObj1, sourceObj11);
console.log(targetObj1); // {a: 1, b: 1, c: 3}

…的用法

对象中的扩展运算符(…)用于取出参数对象中的所有可遍历属性,拷贝到当前对象之中

let bar = {a:1,b:2}
let baz = ...bar
console.log(baz) // {a:1,b:2}

如果有同名属性则会覆盖

let bar = {a: 1, b: 2};
let baz = {...bar, ...{a:2, b: 4}}; 
console.log(baz) // {a: 2, b: 4}

也可以用来复制数组

const arr1 = [1, 2];
const arr2 = [...arr1]; // arr2的值是[1, 2]

用来拆分数组

const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest  // [2, 3, 4, 5]

用来转换字符串为数组

[...'hello']
// [ "h", "e", "l", "l", "o" ]

用来取参数

// arguments对象
function foo() {
  const args = [...arguments];
}

用来进行汇率计算

 function coveryCurrency(rate, ...amounts) {
    return amounts.map(amount => amount * rate)
    }
    console.log(coveryCurrency(0.2, 1, 2, 3,54))

拼接数组

 const arr1 = ['sd', 'dsf'];
  const arr2 = ['ds','ujtgj'];
  const arr3 = [...arr1, '拼接', ...arr2]
  console.log(arr3) // ["sd", "dsf", "拼接", "ds", "ujtgj"]

函数传参
用于复制数组,如果数组姐赋值会导致改了一个另外一个也改了,使用…就不会有这个问题了

用来新增数组
有两种做法
1、传统做法

let a = [1, 2, 3]
let b = [];
b.push.apply(b, a)

2、es6做法
b.push(…a)

let dateArr = [2019,8,1]
date = new Date(dateArr[0],dateArr[1],dateArr[2]) //以前的呆板方法
date1 = new Date(...dateArr)
Sun Sep 01 2019 00:00:00 GMT+0800 (中国标准时间) // es6方法

_.extend

与之类型的还有 lodash里面的_.extend
也是用于复制对象

 cloneEditUser(currentUser: OuUser | User): User {
    return {
      id: currentUser.id,
      name: currentUser.name,
      remarks: currentUser.remarks,
      customAttributes: _.extend({}, currentUser.customAttributes)
    };
  }
let bar = {a: 1, b: 2};
let baa = _.extend({},bar) // 这里baa的值是 {a: 1, b: 2}
let baaa = _.extend({c:3},bar) // 这里baaa的值是 {c:3, a: 1, b: 2} 这个函数会直接加到后面

Array.of和Array.from

Array.from用于将类数组对象转换位数组
Array.of 用于创建数组,过滤underfine

let a = Array.of(1)
console.log(a) //结果是[1]不是[undefined]

find方法

 const inventory = [
            {name: 'sad0', age:2},
            {name: 'sad1', age:3},
            {name: 'sad2', age:4},
        ]
console.log('目标对象',inventory.findIndex((a,index,aa) => index == 2)) // 目标对象 {name: 'sad2', age:4}
console.log('目标下标',inventory.findIndex((a,index,aa) => index == 2)) // 目标下标 2

说明: 这里默认3个参数 (element, index, array) 遍历的对象 遍历的下标 整个数组

some和every

 const inventory = [
            {name: 'sad0', age:2},
            {name: 'sad1', age:3},
            {name: 'sad2', age:4},
        ]
console.log(inventory.some(a => a.age > 2)) // true
console.log(inventory.every(a => a.age > 2)) // false

some只要有一个满足条件就会停止遍历然后返回true, every只要有一个不满足条件就会返回false

lambda表达式

filter过滤

let features: Feature[] = vectorSource.getFeatures().filter(filterFeature => {
        return filterFeature.get("sensorId") == feature.get("sensorId");
    });

多行filter

relatedSensorReports: this.weeklyReports.filter(
     r =>
        report.parents.indexOf(r.sensorId) >= 0 ||
        report.children.indexOf(r.sensorId) >= 0
    )

find

  getDistrictName(code: string) {
    return this.districtList.find(d => d.code == code)!.name;
  }

快速创建对象

当对象键值相同的时候,可以省略值的new

  const a = '1';
  const b = '2';
  const c = '3';
  let d = {
      a: a,
      b: b,
      c: c
  }
  console.log(d)

等同于

  const a = '1';
  const b = '2';
  const c = '3';
  let d = {
      a,
      b,
      c
  }
  console.log(d)

函数也可以简写

    let name = `12`;
    let age = 13;
    let brithday = `2019-10-10`;
 const laravist = {
     name,
     age,
     brithday,
     greet: function(){
         alert(`Hello ${this.name}`)
     }
 }
 laravist.greet()

promise

为了防止请求地狱而设计出promise

 let username;
  const userPromise = axios.get('https://api.github.com/users');
  userPromise
    .then(response =>{
        username = response.data[0].login;
        return axios.get(`https://api.github.com/users/${username}/repos`);
    })
    .then(response => {
        console.log(response.data)
    })

自己设计一个promise

 const p = new Promise((resolve, reject) => {
      setTimeout(() => {
        reject('Laravist is awesome!')
      }, 2000);
  });
  p.then(data => {
      console.log(data)
  }).catch(err => {
      console.error(err)
  })

返回正确用resolve,返回错误用reject
多个promise使用Promist.all这个方法

在这里插入图片描述

取地址栏的参数

// 假设地址栏中查询参数是这样 "?post=1234&action=edit"
  
var urlParams = new URLSearchParams(window.location.search);
  
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值