遍历
for in(返回的是数组的索引) 和 for of(返回的是数组的值),PS:不支持json对象
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
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)
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
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
数组去重
const arre=[1,2,3,4,5,5,1]; const rest = [...new Set(arre)]; console.log(rest);//(5) [1, 2, 3, 4, 5]