# study-es6 **Repository Path**: wangk_code/study-es6 ## Basic Information - **Project Name**: study-es6 - **Description**: js es6 语法学习 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2019-10-20 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # study-es6 ## 介绍 js es6 语法学习 ## 教程 https://juejin.im/post/5bfe05505188252098022400 ## 笔记 ### 1、let 和 const const : 声明的变量不能被修改。 let : 局部变量声明,var 作用域不清晰不建议使用。 ``` let a = "x"; const domain = "http://xx.xx.com"; ``` ### 2、模板字符串 - 1、字符串拼接 ``` const address = 'changsha'; // bad const homeAddress = 'hunan ' + address; // good const companyAddress = `hunan ${address} `; ``` - 2、标签模板 ``` const url ="http://www.xx.com"; let html=` ${url}/index.html `; ``` ### 3、箭头函数 - 1、 使用 ``` let show =(title)=>{console.log(title)}; show('name'); // name ``` - 2、避免情况 a) 使用箭头函数定义对象的方法. ``` let foo = { value: 1, getvalue: () => console.log(this.value) } foo.getvalue(); // undefined ``` b) 作为事件的回调函数. ``` // bad const button = document.getElementById('myButton'); button.addEventListener('click', () => { console.log(this === window); // => true this.innerHTML = 'Clicked button'; }); ``` 注意事项: https://www.itcodemonkey.com/article/14003.html ### 4. Symbol 生成一个唯一的值,可以用作常量。 ``` // bad const TYPE_IMAGE='IMAGE'; // good const TYPE_VIDEO =Symbol(); ``` ### 5. Set 和 Map ``` // bad function test(color) { switch (color) { case 'red': return ['apple', 'strawberry']; case 'purple': return ['grape', 'plum'] default: return []; } } console.log(test('red')); // good const fruitColor = { red: ['apple', 'strawberry'], purple: ['grape', 'plum'] }; console.log(fruitColor['red']||[]); // better const fruitColorMap =new Map() .set('red',['apple', 'strawberry']) .set('purple',['grape', 'plum']); console.log(fruitColorMap.get('red')); ``` ### 6、 for of - 1、遍历范围 for...of 循环可以使用的范围包括: 1、数组 2、Set 3、Map 4、类数组对象。 5、Generator 对象 6、字符串 ``` for (const v of ['a', 'b', 'c']) { console.log(v); } // a b c for (const [i, v] of ['a', 'b', 'c'].entries()) { console.log(i, v); } // 0 "a" // 1 "b" // 2 "c" let map = new Map([ ["aaaa"], ["bbbb"] ]); for(let key of map.keys()){ console.log(key); } // aaaa // bbbb ``` ### 7. Promise 解决JS 回调多层嵌套问题 ``` // 例子 7-1 // bad request(url, function(err, res, body) { if (err) handleError(err); fs.writeFile('1.txt', body, function(err) { request(url2, function(err, res, body) { if (err) handleError(err) }) }) }); // good request(url) .then(function(result) { return writeFileAsynv('1.txt', result) }) .then(function(result) { return request(url2) }) .catch(function(e){ handleError(e) }); fetch('file.json') .then(data => data.json()) .catch(error => console.error(error)) .finally(() => console.log('finished')); ``` ### 8. Async 异步任务同步化 - 1、简洁代码 ``` // 例子 8-1 // good function fetch() { return ( fetchData() .then(() => { return "done" }); ) } // better async function fetch() { await fetchData() return "done" }; ``` ``` // good function fetch() { return fetchData() .then(data => { if (data.moreData) { return fetchAnotherData(data) .then(moreData => { return moreData }) } else { return data } }); } // better async function fetch() { const data = await fetchData() if (data.moreData) { const moreData = await fetchAnotherData(data); return moreData } else { return data } }; ``` ``` // good function fetch() { return ( fetchData() .then(value1 => { return fetchMoreData(value1) }) .then(value2 => { return fetchMoreData2(value2) }) ) } // better async function fetch() { const value1 = await fetchData() const value2 = await fetchMoreData(value1) return fetchMoreData2(value2) }; ``` - 2、错误处理 ``` // good function fetch() { try { fetchData() .then(result => { const data = JSON.parse(result) }) .catch((err) => { console.log(err) }) } catch (err) { console.log(err) } } // better async function fetch() { try { const data = JSON.parse(await fetchData()) } catch (err) { console.log(err) } }; ``` - 3、"async 地狱" ``` // bad (async () => { const getList = await getList(); const getAnotherList = await getAnotherList(); })(); // good (async () => { const listPromise = getList(); const anotherListPromise = getAnotherList(); await listPromise; await anotherListPromise; })(); // good (async () => { Promise.all([getList(), getAnotherList()]).then(...); })(); ``` ### 9、Class 采用类的形式,来创建对象 ``` class Apple { constructor(address) { this.address = address; } static color() { return "red"; } } let apple =new Apple("山东"); console.log(Apple.color()); // red console.log(apple.address); // 山东 ``` ### 10、装饰器 装饰器:允许向一个现有的对象添加新的功能,同时又不改变其结构。 具体可参考:https://www.runoob.com/design-pattern/decorator-pattern.html 不是很好理解,后续再完善,先跳过。 ### 11、 函数 - 1、简单类型参数: ``` // bad function test(value) { const v =value||1; return v; } // good function test2(value=1) { const v=value; return v; } ``` - 2、对象参数: ``` // bad function showDetail(model) { const title = model.title != undefined ? config.foo : 'H!'; const age = model.age != undefined ? config.age : '12'; console.log([title, age]); } // good function showDetail2({title = 'H2', age = 100}) { console.log([title, age]); } ``` ### 12、拓展预算符 通过 ... 传递参数。 ``` function orderBy(...a){ return a.sort(); } console.log(orderBy(1,4,4,3,2,4,6)); // [ 1, 2, 3, 4, 4, 4, 6 ] ``` ### 14、析构 - 1、 数组析构: ``` // 数组析构 const str="xxxx_bbbb"; const [arr1,arr2] = str.split('_'); console.log(arr1,arr2); ``` - 2、类析构: ``` // 类析构 let { foo,bar } = { foo: 'aaa', bar: 'bbb' }; console.log([foo,bar]); // [ 'aaa', 'bbb' ] ``` ### 15、增强的对象字面量 - 1、类快速加属性 ``` const a = "something"; const cls = { a }; console.log(cls); // {a: "something"} ``` - 2、 字符串定义属性 ``` const b= "abcd"; const cls ={ ['_b']:b }; console.log(cls); // {_b: "abcd"} ``` ### 16、 数组的拓展 - 1、 keys ``` var arr=[1,2,3,1]; Object.keys(arr); // ["0", "1", "2", "3"] ``` - 2、entries ``` for (let [index, elem] of ['a', 'b'].entries()) { console.log(index, elem); } // 0 "a" // 1 "b" ``` - 3、 values ``` let arr =['a','c','d','e','dd']; for(let v of arr.values()){ console.log(v); } // a // c // d // e // dd ``` - 4、includes ``` if(['a','b','c'].includes('b')){ console.log("include"); } ``` - 5、find ``` ['a','b','c'].find((a)=>{ return a=='a' }) // a ``` - 6、findIndex 返回第一个符合条件的数组项index值 ``` let index=[1,32,3,4,5,6].findIndex((value, index, arr) => { return value > 0 }); //0 ```