异常
抛出异常
//捕获异常 try{ // throw new Error('new error'); // throw new ReferenceError('new error'); // throw new 1; //下面类型不报错,正常抛出 // throw new Number(100); // throw 'not ok'; // throw [1,2,3]; // throw {'a':1}; throw () => {}; }catch(error){ console.log(error) console.log(error.constructor.name); }finally{ console.log('===end===') }
模块化
ES6模块化
导出
//缺省导出 export default class A{ constructor(x){ this.x = x; } show(){ console.log(this.x); } } //导出函数 export function foo(){ console.log('foo function'); } //导出常量 export const CONSTA = 'AAA';
导入
import {A,foo} from ".src/moda"
import * as mod_a from "/src/moda"
转译工具
babel
function * counter(){ let i=0; while (true){ yield (++i); } } g = counter(); console.log(g.next().value);
预设
离线转译安装配置(*)
1.初始化npm
2.设置镜像
3.安装
4.修改package.json
5.准备目录
6.配置babel和安装依赖
7.准备js文件
//######moda.js###### //缺省导出 export default function a(){ console.log("moda.a()"); } //导出函数 export function b(){ console.log('moda.b()'); } //导出常量 export let c = '100'; export var d = 220; export const e = 300;
//###index.js#### // import a from "./moda"; import {b,c,d,e} from "./moda"; // a(); b(); console.log(c,d,e);
导入导出
缺省导入导出
//缺省导出 export default function(){ console.log("default export function") } //缺省导出,命名函数 export default function xyz(){ console.log('default export function') }
//缺省导入 import defaultFunc from './moda' defaultFunc();
命名导入导出
//命名导出函数 export function foo(){ console.log('regular foo()') } //函数定义 function bar(){ console.log('regular bar()') } //变量常量定义 let x = 100; var y = 200; const z = 300; //导出 export {bar,x,y,z};
//导入:as 设置别名 import defaultCls,{foo,bar,x,y,z as CONST_C} from "./moda" foo(); bar(); console.log(x); console.log(y); console.log(CONST_C); new defaultCls(1000).show();
import * as newmod from "./moda" newmod.foo(); newmod.bar(); console.log(newmod.x); new newmod.default(200).show();
解构
JS的解构很灵活,参考 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Spread_syntax
列表解构
var parts = ['shoulder','knees']; var lyrics = ['head',...parts,'and','toes']; //使用...parts解构 console.log(lyrics)
参数解构
//参数解构 function f(x,y,z){ console.log(x,y,z) } var args = [2,3,4]; f(...args)
数组解构
const arr= [100,200,300]; let [x,y,z] = arr; console.log(1,x,y,z) //1 100 200 300 //丢弃 const [,d,] = arr; console.log(2,d) //2 200 //少于数组元素 const [e,f] = arr; console.log(3,e,f) //3 100 200 //多余数组元素 const [i,j,k,l] = arr; console.log(4,i,j,k,l) //4 100 200 300 undefined //可变变量 const [o,...args] = arr; console.log(5,o); //5 100 console.log(5,args) //5 [ 200, 300 ] //支持默认值 const [q=1,w,,,r=10] = arr; console.log(6,q,w,r) //6 100 200 10
对象解构
//对象解构 const obj = { a:100, b:200, c:300 }; let {x,y,z} = obj; console.log(1,x,y,z) //1 undefined undefined undefined let {a,b,c} = obj; //key名称 console.log(2,a,b,c) //2 100 200 300 let {a:M,b:N,d:D='python'} = obj;//重命名、缺省值 console.log(3,M,N,D) //3 100 200 python
复杂结构
onst arr = [1,[2,3],4]; const [a,[b,c],d] = arr; console.log(1,a,b,c,d) //1 1 2 3 4 const [e,f] = arr; console.log(2,e,f) //2 1 [ 2, 3 ] const [g,h,i,j=18] = arr; console.log(3,g,h,i,j) //3 1 [ 2, 3 ] 4 18 const [k,...l] = arr; console.log(4,k,l) //4 1 [ [ 2, 3 ], 4 ]
//对象 var metadata ={ title:'Scartch', translations:[ { locale:"de", location_tags:[], url:"/de/docs/Tools/Scartch", title:'JavaScript-Umegebung' } ], url:"/etc/network/Scartch" } var {title:enTitle,translations:[{title:locationTitle}]} = metadata; console.log(enTitle) //Scartch console.log(locationTitle) //JavaScript-Umegebung
数组的操作
const arr= [1,2,3,4,5]; arr.push(6,7); console.log(arr); //[ 1, 2, 3, 4, 5, 6, 7] arr.pop() console.log(arr); //[ 1, 2, 3, 4, 5, 6 ] //map有返回值 console.log(arr.map(x => x*x)); //[ 1, 4, 9, 16, 25, 36 ] //filter有返回值 console.log(arr.filter(x => x%2==0)); //[ 2, 4, 6 ] // console.log(arr.filter(x => !(x%2))) //foreach无返回值 const newarr = arr.forEach(x => x=10); console.log(newarr) //undefined
数组练习
const s = Math.sqrt(10) const arr = [1,2,3,4,5]; //1 console.log(arr.filter(x => !(x%2)).map(x => x*x).filter(x => x>10)); //2 console.log(arr.filter(x => !(x%2) && x>s).map(x => x*x)) //3 let newarr = [] arr.forEach(x => { if (x>s && !(x%2)) newarr.push(x*x); }) console.log(newarr) //先过滤再求值
对象的操作
const obj = { a:100, b:200, c:300 } console.log(Object.keys(obj)) //[ 'a', 'b', 'c' ] console.log(Object.values(obj)) //[ 100, 200, 300 ] console.log(Object.entries(obj)) //[ [ 'a', 100 ], [ 'b', 200 ], [ 'c', 300 ] ] //assign var metadata ={ title:'Scartch', translations:[ { locale:"de", location_tags:[], url:"/de/docs/Tools/Scartch", title:'JavaScript-Umegebung' } ], url:"/etc/network/Scartch" } var copy = Object.assign({}/*对象目标*/,metadata, {schoolName:'magedu',url:"www.magedu.com"}, // 增加新的属性,覆盖同名属性 {translations:null} //覆盖metadata的translations ) console.log(copy)
Promise
概念
execotor
promise的状态
Promise.then(onFulfilled,onRejected)
//简单示例 var myPromise= new Promise((resolve,reject) => { resolve('hello'); //执行,置状态为fulfilled console.log(`~~~~~~~~~`); reject('world'); //永远执行不到 }); console.log(myPromise) myPromise.then( /*如果成功则显示结果 */ (value) => console.log(1,myPromise,value), /*如果失败则显示原因*/ (reason) => console.log(2,myPromise,reason) ); /*运行结果1: ~~~~~~~~~ Promise { 'hello' } 1 Promise { 'hello' } hello */ /*运行结果2(屏蔽resolve('hello');): ~~~~~~~~~ Promise { <rejected> 'world' } 2 Promise { <rejected> 'world' } world */
catch(onRejected)
var myPromise= new Promise((resolve,reject) => { resolve('hello'); //执行,置状态为fulfilled console.log(`~~~~~~~~~`); reject('world'); //永远执行不到 }); console.log(myPromise) //Promise { <rejected> 'world' } //Promise { 'hello' } const test = myPromise.then( /*如果成功则显示结果 */ (value) => console.log(1,myPromise,value), //1 Promise { 'hello' } hello /*如果失败则显示原因*/ (reason) => console.log(2,myPromise,reason) //2 Promise { <rejected> 'world' } world ).then( function (value){ console.log(2.5,value); //2.5 undefined //2.5 undefined return Promise.reject(value+`***`) } ).catch(reason => { console.log(3,reason); //3 undefined*** return Promise.resolve(reason); //3 undefined*** }) console.log(4,test) //4 Promise { <pending> } //4 Promise { <pending> }
异步实例
//异步实例 function runAsync(){ return new Promise(function(resolve,reject){ //异步操作 setTimeout(function(){ console.log('do sth...'); resolve(`ok...`); },3000); }); } //调用 runAsync().then(value => { console.log(value); return Promise.reject(value+'*'); }).catch(reason => { console.log(reason); return Promise.resolve(reason+'*'); }).then(value => { console.log(value); console.log('End') }); console.log('~~~~~~~FIN~~~~~'); /*输出结果: ~~~~~~~FIN~~~~~ do sth... ok... ok...* ok...** End */