文章目录
- 注意事项
- 1.声明变量
- 2.定义常量
- 3.解构赋值
- 4.模板字符串
- 5.简化对象写法
- 6.箭头函数
- 7.参数默认值
- 8.rest参数
- 9.扩展运算符
- 10.Symbol
- 11.生成器函数
- 12.Promise基本语法
- 13.集合set
- 14.Map
- 15.类class
- 16.数值扩展
- 17.对象私有属性
- 18.对象方法扩展
- 19.js文件模块化
- 20.async和await
- 21.正则扩展-正向断言与反向断言
- 22.可选链操作符
- 23.动态import
注意事项
代码中的注释有笔记如
// 1.变量不能重复声明
有一些错误示范代码,为了代码整体可运行,将其注释如
let star='jaychou';
// let star='jollin'
// Uncaught SyntaxError: Identifier 'star' has already been declared
当代码有输出是,通常将输出放在对应代码下一行,并注释如下
// let star='jollin'
// Uncaught SyntaxError: Identifier 'star' has already been declaredconst TEAM = ['70KG','baisha'];
TEAM.push('MAZHE');
console.log(TEAM);
// ['70KG', 'baisha', 'MAZHE']
1.声明变量
<script>let a;let b,c,d;let e=100;let f=521, g='iloveyou', h=[];// 1.变量不能重复声明let star='jaychou';// let star='jollin'// Uncaught SyntaxError: Identifier 'star' has already been declared// 2.块级作用域,全局,函数,eval// if else while for{let girl='jollin';}// console.log(girl);// Uncaught ReferenceError: girl is not defined// 3.不存在变量提升// console.log(boy);// Uncaught ReferenceError: Cannot access 'boy' before initializationlet boy='jaychou';// 4.不影响作用域链{let school='xxschool';function fn(){console.log(school);}fn();}
</script>
2.定义常量
<script>// 声明常量const SCHOOL = 'xxschool'// 1.一定要赋初始值// const A;// Uncaught SyntaxError: Missing initializer in const declaration// 2.一般常量使用大写// 3.常量的值不能修改// SCHOOL='yyschool'// Uncaught TypeError: Assignment to constant variable.// 4.块级作用域{const PLAYER='70KG';}// console.log(PLAYER);// Uncaught ReferenceError: PLAYER is not defined// 5.对于数组和对象的元素修改,不算做对常量的修改,不会报错const TEAM = ['70KG','baisha'];TEAM.push('MAZHE');console.log(TEAM);// ['70KG', 'baisha', 'MAZHE']
</script>
3.解构赋值
<script>// ES6允许按照一定模式从数组和对象中提取值,对变量进行赋值,称为解构赋值。// 1.数组的解构const F4 = ['A1','B2','C3','D4'];let [A,B,C,D] = F4;console.log(A,B,C,D);// A1 B2 C3 D4// 2.对象的解构const zhou = {name:'jaychou',age:'40',skill: function(){console.log('我可以唱歌');}};let {name,age,skill} = zhou;console.log(name,age,skill);// jaychou 40 ƒ (){// console.log('我可以唱歌');// }
</script>
4.模板字符串
<script>// ES6引入新的字符串声明方式``// 1.声明let str1 = `这是一个字符串`;console.log(str1);// 这是一个字符串// 2.内容中可以出现换行符let str2 = `<ul><li>A1</li><li>B2</li><li>C3</li><li>D4</li></ul>`// 3.变量拼接let star = '周杰伦';let str3 = `我最喜欢听${star}的歌曲`console.log(str3)// 我最喜欢听周杰伦的歌曲
</script>
5.简化对象写法
<script>// ES6允许在大括号里,直接写入变量和函数,作为对象的属性和方法let name = 'jaychou';let skill = function(){console.log('i can sing');}const star = {name,skill,age(){console.log('40');}}console.log(star);// {name: 'jaychou', skill: ƒ, age: ƒ}
</script>
6.箭头函数
<script>// ES6允许使用箭头(=>)定义函数// 声明一个函数let skill=function(a,b){return a+b;}let skill2=(a,b)=>{return a+b;}// 调用函数let result = skill(1,2);let result2 = skill(2,4);console.log(result);// 3console.log(result2);// 6// 1.this是静态的,this始终指向函数声明时所在作用域下的this的值function getName(){console.log(this.name);}let getName2 = () => {console.log(this.name);}// 设置window对象的name属性window.name = 'name of window';const star={name:'jaychou'}// 直接调用getName();// name of windowgetName2();// name of window// call 方法调用getName.call(star);// jaychougetName2.call(star);// name of window// 2.不能作为构造实例化对象let Person=(name,age)=>{this.name=name;this.age=age;}// let me=new Person('xiaoming','30');// Uncaught TypeError: Person is not a constructor// 3.不能使用arguments变量// let fun=()=>{// console.log(arguments);// }// fun(1,2,3);// Uncaught ReferenceError: arguments is not defined// 4.箭头函数的简写// 1).省略小括号,形参只有一个的时候let add=n=>{return n+n;}console.log(add(3))// 6// 2). 省略花括号,当代码只有一条语句的时候,此时return必须省略,// 而且语句的执行结果就是函数的返回值let square = n => n*n;console.log(square(4))// 16// 示例:从数组中返回偶数的元素const arr=[1,6,9,100,10];const even_result = arr.filter(function(item){if (item%2===0){return true;}else{return false;}})console.log(even_result);// [6, 100, 10]const even_result2 = arr.filter(item=>item%2===0)console.log(even_result2);// [6, 100, 10]
</script>
箭头函数适合与this无关的回调,定时器,数组的方法回调
不适合与this有关的回调,时间回调,对象的方法
7.参数默认值
<script>// ES6允许给函数的参数赋值初始值// 1.形参初始值,具有默认的参数,一般位置要靠后function add(a, b, c = 10) {return a + b + c;}let result = add(1, 2)console.log(result);// 13// 2.与解构赋值结合function connect({host = '127.0.0.1', port, username, password}) {console.log(host);console.log(port);console.log(username);console.log(password);}connect({host: 'localhost',port: '3306',username: 'username',password: 'password',})// localhost// 3306// username// password
</script>
8.rest参数
<script>// ES6引入rest参数,用于获取函数的实参,用来代替arguments// ES5获取实参的方式function date(){console.log(arguments);}date('girl1','girl2','girl3')// Arguments(3) ['girl1', 'girl2', 'girl3', callee: ƒ, Symbol(Symbol.iterator): ƒ]// rest参数function date2(...args){console.log(args);}date2('girl1','girl2','girl3')// (3) ['girl1', 'girl2', 'girl3']function fun(a,b,...args){console.log(a);console.log(b);console.log(args);}fun(1,2,3,4,5,6);// 1// 2// (4) [3, 4, 5, 6]
</script>
9.扩展运算符
<div></div>
<div></div>
<div></div>
<script>// 扩展运算符能将数组转换为逗号分割的参数序列const f4=['f1','f2','f3','f4']function singer(){console.log(arguments);}singer(...f4);// Arguments(4) ['f1', 'f2', 'f3', 'f4', callee: ƒ, Symbol(Symbol.iterator): ƒ]// 应用1.数组的合并const boys=['boy1','boy2'];const girls=['girl1','girl2'];const boysAndGirls=boys.concat(girls)const boysAndGirls2=[...boys,...girls]console.log(boysAndGirls);// (4) ['boy1', 'boy2', 'girl1', 'girl2']console.log(boysAndGirls2);// (4) ['boy1', 'boy2', 'girl1', 'girl2']// 应用2.数组的克隆const fruits=['apple','banana','orange'];const fruits2 = [...fruits]console.log(fruits);// 将伪数组转换成真正的数组const divs = document.querySelectorAll('div');const divArr = [...divs];console.log(divs);// NodeList(3) [div, div, div]console.log(divArr);// (3) [div, div, div]
</script>
10.Symbol
<script>// 创建Symbollet s=Symbol();let s2 = Symbol('abcd');let s3 = Symbol.for('ABCD');console.log(s, typeof s);// Symbol() 'symbol'console.log(s2, typeof s2);// Symbol(abcd) 'symbol'console.log(s3, typeof s3);// Symbol(ABCD) 'symbol'// 不能与其他类型数据进行运算// 数据类型巧记 USONB: YOU SO NB// U: undefined// S: String, Symbol// O: Object// N: null, Number// B: Boolean// Symbol创建对象属性// 向对象中添加方法up downlet game = {name:'俄罗斯方块'}let methods = {up: Symbol('up'),down: Symbol('down')};game[methods.up] = function(){console.log('我可以改变形状');}game[methods.down] = function(){console.log('我可以快速下降');}console.log(game);// {name: '俄罗斯方块', Symbol(up): ƒ, Symbol(down): ƒ}let game2 = {name:'狼人杀',[Symbol('say')]: function(){console.log('我可以发言');},[Symbol('zibao')]: function(){console.log('我可以自爆');},}console.log(game2)// {name: '俄罗斯方块', Symbol(up): ƒ, Symbol(down): ƒ}
</script>
11.生成器函数
<script>// 生成器其实就是一个特殊的函数function* gen() {yield 'alpha';yield 'bob';yield 'charlie';}let iterator = gen();console.log(iterator.next());// {value: 'alpha', done: false}console.log(iterator.next());// {value: 'bob', done: false}console.log(iterator.next());// {value: 'charlie', done: false}console.log(iterator.next());// {value: undefined, done: true}// 遍历for (let v of gen()) {console.log(v);}// alpha// bob// charlie// 生成器函数实例// 回调地狱// setTimeout(() => {// console.log(111);// setTimeout(() => {// console.log(222);// setTimeout(() => {// console.log(333);// },3000)// },2000)// },1000)function one() {setTimeout(() => {console.log(111);iterator2.next();},1000)}function two() {setTimeout(() => {console.log(222);iterator2.next();},2000)}function three() {setTimeout(() => {console.log(333);iterator2.next();},3000)}function * gen2(){yield one();yield two();yield three();}let iterator2=gen2();iterator2.next();// 1秒后输出:111// 2秒后输出:222// 3秒后输出:333</script>
12.Promise基本语法
<script>// 实例化 Promise 对象const p = new Promise(function(resolve,reject){setTimeout(function(){let data = '用户数据';resolve(data);// let err='错误信息';// reject(err);},1000);});// 调用 Promise 对象的then方法p.then(function(value){console.log(value);},function(reason){console.error(reason);})// 1秒后输出:用户数据
</script>
13.集合set
<script>// set的声明let s= new Set(['a','b','c']);let s2 = new Set(['A','B','C','D','E'])// 元素个数console.log(s2.size);// 5// 添加新元素s2.add('F');console.log(s2);// Set(6) {'A', 'B', 'C', 'D', 'E', …}// 删除元素s2.delete('A');console.log(s2);// Set(5) {'B', 'C', 'D', 'E', 'F'}// 查询元素console.log(s2.has('C'));// trueconsole.log(s2.has('O'));// false// 清空s2.clear();console.log(s2)// Set(0) {size: 0}// 遍历for(let v of s){console.log(v)}// a// b// c
</script>
14.Map
<script>// 声明Maplet m = new Map();// 添加元素m.set('name','jaychou');m.set('skill',function(){console.log('我可以唱歌!');});let key={star:'jollin'};m.set(key,['value1','value2','value3']);// sizeconsole.log(m.size)// 3// 删除m.delete('name');// 获取console.log(m.get('skill'));// ƒ (){// console.log('我可以唱歌!');// }console.log(m.get(key));// (3) ['value1', 'value2', 'value3']// 清空m.clear();
</script>
15.类class
<script>// 构造一个类class MobilePhone{// 构造方法,名字不能修改constructor(brand,price){this.brand = brand;this.price = price;}// 方法必须使用该语法,不能使用ES5的对象完整形式call(){console.log('我可以打电话')}}let onePlus = new MobilePhone("1+",2000);console.log(onePlus);// MobilePhone {brand: '1+', price: 2000}
</script>
16.数值扩展
<script>// 0.Number.EPSILON 是JavaScript表示的最小精度function equal(a,b){if (Math.abs(a-b)<Number.EPSILON){return true;}else{return false;}}console.log(0.1+0.2===0.3);// falseconsole.log(equal(0.1+0.2,0.3));// true// 1.二进制和八进制let b=0b1010;let o=0o177;let d=200;let x=0xff;console.log(x);// 255// 2.Number.isFinite检查一个值是否为有限数console.log(Number.isFinite(100));// trueconsole.log(Number.isFinite(100/0));// falseconsole.log(Number.isFinite(Infinity));// false// 3.Number.parseInt Number.parseFloat字符串转整数console.log(Number.parseInt('312123123abc'));// 312123123console.log(Number.parseFloat('3.231232131dii'));// 3.231232131// 4.Number.isNaN检查一个数值是否为NaNconsole.log(Number.isNaN(23));// false// 5.Number.isInteger 判断是否整数// 6.Math.trunc 抹掉小数部分// 7.Math.sign 判断一个数符号console.log(Math.sign(100));// 1console.log(Math.sign(0));// 0console.log(Math.sign(-2000));// -1
</script>
17.对象私有属性
<script>class Person{// 公有属性name;// 私有属性#age;#weight;// 构造方法constructor(name,age,weight){this.name=name;this.#age=age;this.#weight=weight;}intro(){console.log(this.name);console.log(this.#age);console.log(this.#weight);}}let girl=new Person('nana','23','45');console.log(girl.name);console.log(girl.age);console.log(girl.weight);// nana// undefined// undefinedgirl.intro();// nana// 23// 45
</script>
18.对象方法扩展
<script>// 1.Object.is 两个值是否完全相等console.log(Object.is(120, 120));// trueconsole.log(Object.is(NaN, NaN));// trueconsole.log(NaN === NaN);// false// 2.Object.assign对象的合并const config1 = {host: 'localhost',port: 3306,name: 'root',pass: 'root'};const config2 = {host: 'localhost',port: 33060,name: 'name',pass: 'pass'}console.log(Object.assign(config1, config2));// {host: 'localhost', port: 33060, name: 'name', pass: 'pass'}// 3.Object.setPrototypeOf Object.getPrototypeOf// Object.setPrototypeOf() 静态方法可以将一个指定对象的原型// (即内部的 [[Prototype]] 属性)设置为另一个对象或者 null。const obj = {};const parent = { foo: 'bar' };console.log(obj.foo);// undefinedObject.setPrototypeOf(obj, parent);console.log(obj.foo);// barconsole.log(Object.getPrototypeOf(obj))// {foo: 'bar'}
</script>
19.js文件模块化
ES6模块暴露数据,m1.js
// 分别暴露
export let star='jaychou';export function skill() {console.log('i can sing');
}// 统一暴露
let movie='Titanic';function category(){console.log('romance')
}export{movie,category};// 默认暴露
export default{music:'Scarborough Fair',singer: function(){console.log('sarah brightman');}
}
ES6引入模块数据,html
文件
<script type="module">// 1.通用导入方式import * as m1 from './m1.js';// 2.解构赋值方式import {star,skill} from './m1.js';import {movie as mv, category} from './m1.js';import {default as dft} from './m1.js';// 针对默认暴露import dft2 from './m1.js';console.log(dft2);// {music: 'Scarborough Fair', singer: ƒ}
</script>
20.async和await
<script>// 创建promise对象const p = new Promise((resolve, reject) => {// resolve("user data");reject('error occured');})// await要放在async函数中async function main() {try {let rst = await p;console.log(rst);} catch (e) {console.log(e);}}main();// error occured
</script>
21.正则扩展-正向断言与反向断言
<script>// 声明字符串let str = 'js3232323hahaoo44gaga';// 正向断言const reg=/\d+(?=ga)/;const rst = reg.exec(str);console.log(rst);// (1) ['44', index: 15, input: 'js3232323hahaoo44gaga', groups: undefined]// 反向断言const reg2=/(?<=o)\d+/;const rst2=reg2.exec(str);console.log(rst2);// (1) ['44', index: 15, input: 'js3232323hahaoo44gaga', groups: undefined]
</script>
22.可选链操作符
<script>// ?.function main(config) {const dbHost = config && config.db && config.db.host;const dbHost2 = config?.cache?.host;console.log(dbHost);console.log(dbHost2);}main({db: {host: '192.168.1.1',username: 'dbuser',},cache: {host: '192.168.1.1',username: 'cacheuser'}})// 192.168.1.1// 192.168.1.1
</script>
23.动态import
hello.js
export function ok(){alert('nihao!');
}
m1.js
const btn = document.getElementById('btn');btn.onclick = function(){import('./hello.js').then(module=>{module.ok();})
}