ES6编程风格(中)
遍历
for in(返回的是数组的索引) 和 for of(返回的是数组的值),PS:不支持json对象
1 2 3 4 5 6 7 8 9 10 11 | const arr = [ "a" , "b" , "c" ]; const obj ={a: "1" ,b: "2" ,c: "3" ,}; for (let i in arr){ console.log(i); //1 2 3 } for (let v of arr){ console.log(v); //a b c } for (let v of obj){ console.log(v); //obj is not iterable 报错 } |
class 类,命名要大写+set+get+static
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class Person{ //父类 constructor(age){ this .age=age; } tell(){ console.log(`小王的年龄是${ this .age}`); } } const xiaowang = new Person(30); console.log(xiaowang.age); //30 xiaowang.tell(); //小王的年龄是30 class Man extends Person{ //子类实现了继承了父类 //想实现重载或重写的话,先调用父类的方法 constructor(age){ super (age); this .arr=[]; } //重写tell方法 tell(){ //必须要先调一下,不然不支持多个参数的重载 super .tell(); console.log( "hallo" ); } //get和set是不需要主动调用的,外面直接赋值就行 set menu(data){ this .arr.push(data);} get menu(){ return this .arr;} //static static init(){ console.log( "static" ) } } const xiao= new Man(20); console.log(xiao.age); //20 xiao.tell(); //hallo xiao.menu = 'get' ; console.log(xiao.menu); //["get"] Man.init(); //static |
Set是一个集合 + Map(键值对,没有key)
1 2 3 4 5 6 7 8 9 10 11 12 13 | let arrs = new Set( "123" ); arrs.add( "0" ); arrs.add( "0" ); //同样的东西add进来是不管的,只add一个 arrs. delete ( "2" ); //删除 for (let data of arrs){ console.log(data); //1 3 0 } console.log(arrs); //Set(4) {"1", "2", "3", "0"} console.log(arrs.size); //4 console.log(arrs.has( "1" )); //true console.log(arrs.has( "2" )); //false arrs.clear(); //清除 console.log(arrs.size); //0 |
Map
1 2 3 4 5 6 7 8 9 10 | let food = new Map(); let result = {},cook = function (){}; //这些都可以作为一个key,也是map神奇的地方 food.set(result, 'rr' ); food.set(cook, 'rrs' ); console.log(food); //Map(2) {{…} => "rr", ƒ => "rrs"} console.log(food.get(result)); //rr console.log(food.get(cook)); //rrs console.log(food.size); //2 food. delete (result); console.log(food.size); //1 |
数组去重
1 2 3 | const arre=[1,2,3,4,5,5,1]; const rest = [... new Set(arre)]; console.log(rest); //(5) [1, 2, 3, 4, 5] |
点击查看更多内容
为 TA 点赞
0 评论
共同学习,写下你的评论
暂无评论
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦