集合、Map、class


集合介绍与API

声明一个set

//声明一个set
let s = new Set();
let s2 = new Set(['1','2','3','4'])
console.log(s2)

元素个数

console.log(s2.size)

添加新的元素

s2.add('5')
console.log(s2)

删除元素

s2.delete('4')

检测

s2.has('1')  //检测set里面是否有1  有的话就就返回true

清空

s2.clear()

遍历

for(let v of s2){
    console.log(v)
}

集合实践

let arr = [1,2,3,4,5,4,3,2,1]
//1.数组去重
let result = [...new Set(arr)]
console.log(result)
//2.交集
let arr2 = [4,5,6,5,6,]
let result = [...new Set(arr)].filter(item => {
    let s2 = new Set(arr2)
    if(s2.has(item)){
        return true
    }else{
        return false
    }
})
console.log(result)
//3.并集
let result = [...new Set([...arr, ...arr2])]
//4.差集
let diff = [...new Set(arr)].filter(item => !(new Set(arr2).has(item)))

Map

声明一个Map

let m = new Map()

添加元素

m.set('name','尚硅谷')
let key = {
    school:'heiheihei'
}
m.set(key,['bj','sh','shenzhen'])
console.log(m)
//size
console.log(m.size) //2

5mXiEq.png

删除

m.delete('name')

获取

console.log(m.get('name'))   //get后面跟键值

清空

m.clear()

遍历

for(let v of m){
    console.log(v)
}

Class

ES5
//手机
function Phone(brand,price){
    this.brand = brand 
    this.price = price
}
//添加方法
Phone.prototype.call = function(){
    console.log('我可以打电话')
}
//实例化对象
let Huawei = new Phone('华为',5999)
Huawei.call()
console.log(Huawei)

ES6
class Phone{
    //构造方法 名字不能修改
    constructor(brand,price){
        this.brand = brand 
    	this.price = price
    }
    //方法必须使用该㞏,不能使用ES5的对象完整形式
    call(){
        console.log('我可以打电话')
    }
}
let oneplus = new Phone('1+',1999)
console.log(onePlus)

ES5构造函数继承

function Phone(brand,price){
    this.brand = brand
    this.price = price
}
Phone.prototype.call = function(){
    console.log('我可以打电话')
}
function SmartPhone(brand,price,color,size){
    Phone.call(this,brand,price)
    this.color = color
    this.size = size
}
//设置子级构造函数的原型
SmartPhone.prototype == new Phone
SmartPhone.prototype.constructor = SmartPhone
//声明子类的方法
SmartPhone.prototype.photo = function(){
    console.log('我可以拍照')
}
Smartphone.prototype.playGame = function(){
    console.log('我可以玩游戏')
}
const chuizi = new SmartPhone('锤子','2499','黑色','5.5inch')
console.log(chuizi)

class类继承

class Phone{
    //构造方法
    constructor(brand,price){
        this.brand = brand
        this.price = price
    }
    //父类的成员属性
    call(){
        console.log('我可以打电话')
    }
}
class SmartPhone extends Phone{
    //构造方法
    constructor(brand,price,color,size){
        super(brand,price)
        this.color = color
        this.size = size
    }
    photo(){
        console.log('拍照')
    }
    playGame(){
        console.log('玩游戏')
    }
}
const xiaomi = new SmartPhone('小米',799,'黑色','4.')

文章作者: Daniel Lin
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Daniel Lin !
  目录