ES6
let + const
函數(shù)作用域function(){}
var 可以重新賦值 會(huì)有變量提升
塊作用域{}
let 可以重新賦值 在for循環(huán)中屬于整個(gè)循環(huán)
const 不可以重新賦值 對(duì)象屬性可以修改如 person.age = xxx object.freeze(person) 什么都不允許修改
用來(lái)代替立即執(zhí)行函數(shù)
{
const name = 'ruoyu'
}
用于for循環(huán)
for(let i = 1; i < 10; i++){
console.log(i)
setTimeout(function(){
console.log(i:${i}
)
},1000)
}
臨時(shí)性死區(qū)
臨時(shí)性死區(qū) 就是指 let 和 const 有變量提升 但是表現(xiàn)不出來(lái) 等于沒(méi)有變量提升 不能在聲明前console.log
es6中如何使用var let const
默認(rèn)使用const
當(dāng)變量需要重新綁定或者更新的時(shí)候使用let
盡量不使用var
箭頭函數(shù)
箭頭函數(shù)的聲明
刪掉function關(guān)鍵字
加上一個(gè) => 箭頭
沒(méi)有參數(shù)加() 一個(gè)參數(shù)可選擇()寫(xiě)/不寫(xiě) 多個(gè)參數(shù)逗號(hào)分隔(1,2)
get(1,2) => {
return 1 + 2
}
箭頭函數(shù)隱式返回
把return刪除 刪掉花括號(hào){} 把函數(shù)寫(xiě)到一行 如:(number) => number * 2
get(1,2) => 1 + 2
箭頭函數(shù)的this
是詞法作用域 在定義的時(shí)候就被指定 不存在this值的綁定 箭頭函數(shù)的this指的自己的父級(jí)元素的this值
es6函數(shù)默認(rèn)值
function age(a = 18, b = 20) => {
return a * b
}
哪些情況下不宜使用箭頭函數(shù):
1、作為構(gòu)造函數(shù) 或者一個(gè)方法需要綁定到對(duì)象的時(shí)候 如 Person.prototype.updatePoints = () =>{}
2、當(dāng)你真需要this的時(shí)候 如click事件對(duì)象 this會(huì)是windows 所以改用舊版函數(shù) function
3、需要使用arguments對(duì)象的時(shí)候 箭頭函數(shù)沒(méi)有arguments 所以改用舊版函數(shù) function
模板字符串
${}
花括號(hào)里面${}可以是變量 也可以是js表達(dá)式 對(duì)象的屬性 函數(shù) ``可以嵌套
{
const person = 'jelly'
const age = '5'
const sentence = ${person} is ${age * 5} years old.
const template = <div class = 'greet'> <p>Hello</p> </div>
.trim()
}
字符串刪除空格.trim()
<div></div>
.trim() 因?yàn)閌`里會(huì)默認(rèn)保留html的空格 所以需要?jiǎng)h除空格
模板字符串使用
{
const jelly = {
name: 'jelly',
date: '2017-05-07'
todos: [
{name: 'Go to Store', completed: false},
{name: 'Watch Movie', completed: true},
{name: 'Running', completed: true}
]
}
}
const template = <ul> ${jelly.todos.map(todo =>
<li>
{todu.completed ? '√' : '×'} //這里使用三元表達(dá)式 if如果是真[?] 返回√ else[:]返回×
</li>).join('')} </ul>
document.body.innerHTML = template
標(biāo)簽?zāi)0遄址?模板字符串高級(jí))
在模板字符串前使用 函數(shù)名 定義這個(gè)函數(shù) 這個(gè)函數(shù)接收模板字符串作為參數(shù)
函數(shù)的參數(shù)1 是一個(gè)數(shù)組 由模板字符串里的 普通字符串組成
函數(shù)的參數(shù)23456... 是由模板字符串里的變量組成 每個(gè)變量對(duì)應(yīng)一個(gè)參數(shù)
function highlight(strings,...values){
const highlighted = valures.map(value => <span class='highlight'>${values}</span>
)
return strings.reduce((prev.curr,index) => ${prev}${curr}${highlighted[i] || ''}
,'')
}
const user = 'Mary'
const topic = 'Learn to use markdown'
const sentence = highlight${user} has commented on your topic ${topic}
標(biāo)簽?zāi)0暹^(guò)濾用戶輸入:引入凈化工具[DOMPurify] 用標(biāo)簽?zāi)0遄址幚碛脩糨斎?對(duì)用戶的輸入做出一定的凈化
ES6新增字符串方法函數(shù)
1.startsWith("參數(shù)",從哪一位開(kāi)始如6) 從第一位計(jì)算
const id = '51030019800730366x'
id.startsWith('51') //true
id.startsWith('1980',6) //true
const fan = 'I love Laravist.' 大小寫(xiě)敏感
fan.startsWith('i') //false
2.endsWith("參數(shù)1",從哪一位開(kāi)始如6) 從最后計(jì)算 大小寫(xiě)敏感
const id = '51030019800730366x'
id.endsWith('x') //true
id.endsWith('love',6) //true
3.includes("參數(shù)1",從哪一位開(kāi)始如6) 是否包含
const fan = 'I love Laravist.' 大小寫(xiě)敏感
fan.includes('Laravist') //true
fan.includes('Laravist',10) //false 從第10位開(kāi)始沒(méi)有包含 Laravist
4.repeat(次數(shù)) 重復(fù)多少次
'哈'.repeat(3) // '哈哈哈'
對(duì)象解構(gòu)
幫助我們能快速的從對(duì)象中 提取到我們所需要的屬性 可以嵌套
const Tom = {
name: "tom jones"
age: 25
family: {
mother: "norah"
father: "richard"
brother: "howard"
}
}
const {name,age} = Tom
console.log(name)
console.log(age)
//(father: f)是重新命名 聲明了f變量 cat = details 設(shè)置默認(rèn)值 但必須是undifande才能設(shè)置 不是undifande會(huì)使用變量指定的值
const {father: f,brother,cat = 'have cat'} = Tom.family
console.log(f)
console.log(brother)
console.log(cat)
數(shù)組解構(gòu)
const numbers = ['one','two','three','four']
let a = 10
let b = 20
const [one,two] = numbers
const [one,,three] = numbers //獲取0和2位置的兩個(gè)變量值
const [one, ...others] = numbers //獲取0和后面所有的變量值
const [one,two = ‘PHP’] = numbers //設(shè)置默認(rèn)值 但必須是undifande才能設(shè)置
[a,b] = [b,a] //對(duì)象的值交換
for of循環(huán)遍歷
數(shù)組 字符串 map set arguments nodelist...等等的數(shù)據(jù)結(jié)構(gòu) 不支持對(duì)象
相對(duì)于for循環(huán)較簡(jiǎn)單 相對(duì)于for in循環(huán) 每次循環(huán)的是屬性值 相對(duì)于forEach 這個(gè)是支持 終止和跳過(guò) 循環(huán)
不會(huì)遍歷數(shù)組上的非數(shù)值屬性 如function
const fruits = ['apple','Banana','Orange','Mango']
for (let fruit of fruits) {
console.log(fruit)
}
.entries() 同時(shí)獲取索引和值 這里使用了結(jié)構(gòu)的方法
for (let [index,fruit] of fruits.entries()) {
console.log(${fruit} ranks ${index + 1} in my favorite fruits
)
}
for of 用于所有參數(shù)之和
function sum(){
let total = 0
for(let num of arguments){
tatal = tatal + num
}
return total
}
sum (10,23,324,435,34,12)
for of 用于字符串
let name = 'Laravist'
for(let char of name){
console.log(char)
}
ES6新增數(shù)組函數(shù)方法
//常用于dom元素的操作 對(duì)函數(shù)arguments的操作 字符串map數(shù)據(jù)類(lèi)型
Array.from('類(lèi)數(shù)組對(duì)象',參數(shù)2相當(dāng)于map方法) 把 類(lèi)數(shù)組對(duì)象 或是 可遍歷的對(duì)象 轉(zhuǎn)換成一個(gè)真正的數(shù)組
//彌補(bǔ)了Array這個(gè)構(gòu)造函數(shù)的不足 不管你傳入多少參數(shù) 返回的都是這些參數(shù)組成的數(shù)組
Array.of() 保證返回結(jié)果的一致性 肯定返回?cái)?shù)組 傳入1 是1的數(shù)組 傳入(1,2)是兩個(gè)值的數(shù)組
.find() 查找 接受一個(gè)函數(shù)作為參數(shù) 函數(shù)參數(shù):element,index,array
const inventory = [
{name: 'apples', quantity:2},
{name: 'banans', quantity:0},
{name: 'cherries', quantity:5}
]
const bananas = inventory.find(fruit => fruit.name === 'banans')
得到 {name: 'banans', quantity:0}
.findIndex() 查找下標(biāo)
const bananas = inventory.findIndex(fruit => fruit.name === 'banans')
得到 下標(biāo) 1
.some() 滿足一個(gè)直接返回 接收函數(shù)作為參數(shù) 返回布爾值
const isEnough = inventory.some(fruit => fruit.quantity > 0)
得到 true 這里第一個(gè)apples 是滿足的就直接返回了
.every() 滿足所有返回 接收函數(shù)作為參數(shù) 返回布爾值
const isEnough = inventory.some(fruit => fruit.quantity > 0)
得到false 不是所有的參數(shù)都是滿足的 第二個(gè)是0所以是false
剩余參數(shù)
1:
function sum(...numbers){
return numbers.reduce((prev,curr) => prev + curr,0)
}
console.log(sum(1,2,3,4)) 得到10
2:用于參數(shù)
function sum(rate,...numbers){
return numbers.map(number => number * rate)
}
const smounts = sum(0.89,12,34,658,23)
console.log(amounts)
3:用于變量結(jié)構(gòu)
const player = ['jelly',123,5.4,6.7,3.4,7.8,8.9]
const [name,id,...numbers] = player
擴(kuò)展運(yùn)算符
可用于數(shù)組 dom 對(duì)象屬性 對(duì)數(shù)組刪除 得到一個(gè)新數(shù)組
const youngers = ['George','john','Thomas']
const olders = ['james','Adrew','Martin']
const members = [...youngers,'Mary',...olders] //這里擴(kuò)展
const curren = [...members] //這里復(fù)制了members數(shù)組 賦值給curren
curren[0] = 'jelly' //這里修改了下標(biāo)0的值 但是原數(shù)組members的George并沒(méi)有修改
用于函數(shù)
const fruit = ['apple','bananas','pear']
const newFruit = ['orange','mongo']
fruit.push(...newFruit)
console.log(fruit) 得到 fruit = ['apple','bananas','pear','orange','mongo']
時(shí)間函數(shù)
const dateFields = [2017,5,6]
const date = new Date(...dateFields)
對(duì)象字面量的擴(kuò)展 屬性 方法簡(jiǎn)寫(xiě)
當(dāng)對(duì)象數(shù)組擴(kuò)展指的是同一個(gè)變量名字的時(shí)候 不用重復(fù)的寫(xiě)name:name了
函數(shù)方法可以不用重復(fù)寫(xiě) :function
const name = 'Laravist'
const age = 2
const birthday = '2015-09'
const Larvist = {
name,
age,
birthday,
greet(){
console.log(hello${this.name}
)
}
}
用于計(jì)算屬性簡(jiǎn)寫(xiě)
let id = 0
const userIds = {
[user-${++id}
],
[user-${++id}
],
[user-${++id}
]
}
得到 {user-1:1,user-2:2,user-3:3}
const keys = ['name','age','birthday']
const values = ['Laravist',2,'2015-09']
const Larvist = {
[keys.shift()]: values.shift(),
[keys.shift()]: values.shift(),
[keys.shift()]: values.shift(),
}
得到 {name:'Laravist',age: 2,birthday: '2015-09'}
Promise 解決回調(diào)地獄
axios 包支持promiseAPI 幫助我們發(fā)起ajax請(qǐng)求 引入包后
異步編程的反饋 一個(gè)承諾 通常用于調(diào)用api 或 json數(shù)據(jù) 或ajax請(qǐng)求當(dāng)中
當(dāng)你需要某些操作 并且只需要知道它的操作結(jié)果 再進(jìn)行其他事情 而不用暫停等待的時(shí)候 就可以使用Promise
{
let username
const usersPromise = axios.get('http://api.github.com/users') //返回一個(gè)promise 代表promise收到了 給你一個(gè)回應(yīng)
usersPromise.then(reponse => { //then相當(dāng)于事件的on 當(dāng)這件事then的時(shí)候 做一個(gè)什么事
username = reponse.data[0].login
return axios.get('http://api.github.com/users${username}/repos')
}).then(reponse => {
console.log(reponse)
}).catch(err => { //這里.catch 是當(dāng)發(fā)生錯(cuò)誤時(shí) 怎么處理 做什么事
console.error(err)
})
}
自己編寫(xiě)一個(gè)Promise
//創(chuàng)建一個(gè)Promise構(gòu)造函數(shù) 參數(shù)是一個(gè)函數(shù) 然后函數(shù)有兩個(gè)內(nèi)置參數(shù)1.resolve,2.reject
如果這個(gè)Promise是成功的 返回reslove 里傳入成功的數(shù)據(jù) 失敗調(diào)用reject返回失敗的信息
const p = new Promise((resolve,reject) => {
reslove('Laravist is awesome')
setTimeout(() => {
{
reject(Error('Laravist isn 't awesome!')) //Error指明錯(cuò)誤是出現(xiàn)在這一行
}
},2000)
})
p.then(data => {console.log(data)})
.catch(err => {console.error(err)})
.get('http://'); ajax請(qǐng)求
Promise.then 處理回調(diào)地獄 相當(dāng)于事件監(jiān)聽(tīng)
Promise.catch(err => {console.error(err)}) 監(jiān)聽(tīng)處理錯(cuò)誤 如果沒(méi)寫(xiě)發(fā)生錯(cuò)誤就不會(huì)告訴你發(fā)生錯(cuò)誤 只有寫(xiě)了才有
Promise.all([]) 當(dāng)多個(gè)promise完成之后 就返回對(duì)應(yīng)的一個(gè)結(jié)果 結(jié)果的數(shù)組 是和自己傳入的數(shù)組 的順序是一樣的 要都是resolve 才會(huì)執(zhí)行then 如果有一個(gè)結(jié)果是reject 就執(zhí)行catch
Promise.race([]) 由第一個(gè)返回的promise狀態(tài)決定 如果是resolve 執(zhí)行then 如果是reject 執(zhí)行catch
symbol 數(shù)據(jù)類(lèi)型 唯一標(biāo)識(shí)符 解決了對(duì)象命名沖突問(wèn)題
不能遍歷 可以作為私有屬性在對(duì)象內(nèi)部使用
const prter = Symbol('prter') //創(chuàng)建一個(gè)symbol對(duì)象
const student = Symbol('student') //
prter === student 得到false
cosnt classRoom = {
[symbol('lily')]: {grade: 60, gender: 'female'}
[symbol('nina')]: {grade: 80, gender: 'female'}
[symbol('nina')]: {grade: 90, gender: 'female'}
}
可以通過(guò)這個(gè)方法遍歷
const syms = Object.getOwnPropertySymbols(classRomm).map(sym => clasRomm[sym]);
ESlint
可組裝的javaScript和jsx檢查工具
安裝 npm install eslint
生成配置文件 eslint --init 配置文件運(yùn)行環(huán)境: 瀏覽器 'browser': true; 'es6': true; 'commonjs': true
使用檢查命令 eslint xxx.js
自動(dòng)修復(fù)一些問(wèn)題 eslint xxx.js --fix
使用eslint推薦規(guī)則 'extends': 'eslint:recommended'
自己配置的一些規(guī)則寫(xiě)在 'rules'里
找不到Vue 'globals':{'Vue': true}
更多的使用 : http://github.com/airbnb/javascript 這個(gè)書(shū)寫(xiě)規(guī)則
導(dǎo)入導(dǎo)出 模塊
模塊化可以把一些如函數(shù)處理邏輯放到一個(gè)文件里 用模塊導(dǎo)出的方式 供其他文件導(dǎo)入使用相關(guān)處理函數(shù)來(lái)處理數(shù)據(jù)
可以使代碼更干凈舒適 有利于測(cè)試代碼
npm init 生成packge文件
import moment from 'moment' 默認(rèn)導(dǎo)入
import { uniq } from 'lodash'命名導(dǎo)入 必須當(dāng)時(shí)模塊的名字 還需要加{} 可以多個(gè)導(dǎo)出
export { key} 命名導(dǎo)出
export default xxx 默認(rèn)導(dǎo)出 一個(gè)模塊只能有一個(gè)默認(rèn)導(dǎo)出
生成自己的模塊
次文件里:
const apikey = 'abc123'
export default apikey //命名導(dǎo)出 或者 export const apikey = 'abc123' 這是命名導(dǎo)出
主文件里:
import apikey(這個(gè)名字可以自寫(xiě)) from './config' //路徑導(dǎo)入
console.log(apikey)
as 可以改導(dǎo)入或者導(dǎo)出的內(nèi)容重新命名如:
export {apikey as key, age, greet}
import { uniq as apikey } from 'lodash'
導(dǎo)出導(dǎo)入都可以用as來(lái)重命名//導(dǎo)出重命名修改后 要導(dǎo)入時(shí)是導(dǎo)入as后的變量模塊名
使用SustemJS 打包es6 模塊
用于簡(jiǎn)單測(cè)試 或者是寫(xiě)一點(diǎn)小東西的話 是非常有用的
Babel
把es6代碼轉(zhuǎn)換成es5代碼
初始化packge文件 npm init
安裝 npm install babel-cli --save-dev
因?yàn)椴⒉皇侨职惭b的 所以不能在命令行直接使用 所以要在packge文件里的scrits語(yǔ)句
在packge文件里 添加轉(zhuǎn)換es5規(guī)則集:
'babel':{
'presets': ['es2015']
}
polyfill
es6一些新增屬性的補(bǔ)充轉(zhuǎn)換 如from方法 set map方法等... babel的補(bǔ)充轉(zhuǎn)換
最新版本的chrome瀏覽器 不需要polyfill
常用兩個(gè)polyfill :
1、babel的
2、polyfill.io 去百度搜 引入script標(biāo)簽就行
類(lèi)
實(shí)現(xiàn)原形繼承
class是一個(gè)函數(shù) 但是沒(méi)有函數(shù)提升 不能在寫(xiě)在調(diào)用后面 只能通過(guò)new來(lái)調(diào)用
兩種方法
1、類(lèi)的聲明
class User {
}
2、類(lèi)的表達(dá)式
const User = class 名字可選 {
}
constructor 等于之前寫(xiě)的構(gòu)造函數(shù) //function User(name,email){this.name = name; this.email = email}
class里的 info等于之前的 //User.potrotype.info = function(){} 沒(méi)有逗號(hào)
類(lèi)的靜態(tài)方法: static 關(guān)鍵字 只能自己User用 static description () {console.log(I m a user of codecasts.com
)}
User.description 得到 I m a user of codecasts.com
set 關(guān)鍵字方法使用:
codecasts.github = 'Larvist' 得到Larvist
get 關(guān)鍵字方法使用:
codecasts.github 得到 https://github.com/Larvist
方法info 也可以使用計(jì)算屬性的方法來(lái)定義 let methodName = 'info' class里 [methodName] 代替info
class User(){
constructor(name,email){
this.name = name
this.email = email
}
info(){
console.log(`Hi,Im${this.name},my email is ${this.email}`)
}
static descroption(){
console.log(`I m a user of codecasts.com`)
}
set github(value){
this.githubName = value
}
get github(){
return `https://github.com/${this.githubName}`
}
}
const p = new User('codecasts','i@codecasts.com')
類(lèi)class繼承
extends 類(lèi)的繼承 這里Dog 繼承了 Animal
{
子類(lèi)里面用super()來(lái)獲取基類(lèi) this指向Animal name是傳入基類(lèi)需要的name參數(shù)
相等于es5:
function(){
Animal.call(this,name,age)
this.name = name
this.age = age
}
Dog.prototype = new Animal()
Dog.prototype = Dog
}
子類(lèi)的方法和基類(lèi)相同的話 會(huì)覆蓋基類(lèi)的方法
class Animal{
constructor(name){
this.name = name;
this.belly = [];
}
eat(food){
this.belly.push(food)
}
}
class Dog extends Animal {
constructor(name,age){
super(name)
this.age = age
}
bark(){
console.log(`Barl bark`)
}
}
const lucky = new Dog('lucky,2')
class擴(kuò)展內(nèi)建對(duì)象數(shù)組
class MyArray extends Array {
constructor(){
super()
}
}
const colors = new MyArray()
colors[0] = 'red'
console.log(colors.length); 得到 1 因?yàn)橛幸粋€(gè)red
colors.length = 0
console.log(colors.length); 得到 undefined 因?yàn)?設(shè)置為0了
0
lterator 遍歷器
遍歷器就是有一個(gè)對(duì)象 這個(gè)對(duì)象有一個(gè)next()方法 會(huì)返回給我們所需要的數(shù)據(jù)
可遍歷對(duì)象是部署了 Symbol.iterator 屬性的對(duì)象 這個(gè) Symbol.iterator 會(huì)返回給我們一個(gè) 遍歷器
然后每次調(diào)用這個(gè)遍歷對(duì)象的時(shí)候 就會(huì)返回給我們相應(yīng)的值
const colors = ['red','blue','green']
const iterator = colorsSymbol.iterator
console.log(iterator) 返回一個(gè) Array Iterator{}對(duì)象 里面有一個(gè)next()方法
調(diào)用一次
iterator.next() 返回一個(gè)對(duì)象 有兩個(gè)屬性 {value:'red',done:false}
再調(diào)用一次
iterator.next() 返回一個(gè)對(duì)象 有兩個(gè)屬性 {value:'blue',done:false}
再調(diào)用一次
iterator.next() 返回一個(gè)對(duì)象 有兩個(gè)屬性 {value:'green',done:false}
再調(diào)用一次
iterator.next() 返回一個(gè)對(duì)象 有兩個(gè)屬性 {value:undefined,done:true}
ES6當(dāng)中有三種類(lèi)型的集合對(duì)象
1.Arrey
2.map [es6]
3.set [es6]
es6為這三種類(lèi)型 內(nèi)建了遍歷器 可以通過(guò)調(diào)用相應(yīng)的方法來(lái)獲取它們 如:
對(duì)于數(shù)組
const iterator = colors.entries() //entries()返回元素的 屬性名 和 屬性值
const iterator = colors.keys() // 返回元素的索引值
const iterator = colors.values() // 返回元素的值
調(diào)用一次
iterator.next() 返回一個(gè)數(shù)組 {value: Array(2),done:false} //Array(2)里是 0:0下標(biāo) 1:'red'值
調(diào)用一次
iterator.next() 返回一個(gè)數(shù)組 {value: Array(2),done:false} //Array(2)里是 0:1下標(biāo) 1:'blue'值
調(diào)用一次
iterator.next() 返回一個(gè)數(shù)組 {value: Array(2),done:false} //Array(2)里是 0:2下標(biāo) 1:'green'值
調(diào)用一次
iterator.next() 返回一個(gè)數(shù)組 {value: undefined,done:false}
Generator 生成器
生成器是能返回一個(gè)迭代器的函數(shù)
yield 相當(dāng)于 return 但是只是trturn本次執(zhí)行函數(shù)的返回值
調(diào)用colors的時(shí)候不會(huì)執(zhí)行 生成器函數(shù) function* 只有調(diào)用colors.next() 才會(huì)調(diào)用 生成器函數(shù)function*
定義
function* Colors(){
yield 'red'
yield 'green'
yield 'blue'
let i = 0
yield i
i++
yield i
i++
yield i
}
實(shí)例
const colors = Colors();
執(zhí)行調(diào)用
colors.next() 得到{value: 'red', done: false}
Generator應(yīng)用
如控制ajax的工作流
function ajax(url){
axios.get(url).then(res => userGen.next(res.data))
}
function* steps(){
const users = yield ajax('https://api.github.com/users')
const firstUser = yield ajax('https://api.github.com/users/${users[0].login}')
const followers = yield ajax(firstUser.followers_url)
}
const userGen = steps()
userGen.next()
Proxy
能夠幫助我們 重寫(xiě) 一些對(duì)象默認(rèn)方法 賦予我們自定義的邏輯方法
const person = {name:'laravist', age: 2000}
const personProxy = new Proxy(person,{
get(target,key){
return target[key].toUpperCase()
},
set(target,key,value){
if(typeof value === 'string'){
target[key] = value.trim()
}
}
})
personProxy.name = 'codecasts'
personProxy.love = ' i love codecasts '
personProxy.love 得到 'I LOVE CODECASTS'
set 數(shù)組集合類(lèi)型
唯一的數(shù)組 元素不會(huì)有重復(fù)的存在 重復(fù)時(shí)會(huì)忽略
數(shù)字1 和字符串'1' 在set里是兩個(gè)元素
不能通過(guò)索引值來(lái)獲取元素[0]
可以遍歷for of forEach next
實(shí)例
const colors = new Set(['black']);
調(diào)用
colors.add('red')
colors.add('green')
colors.add('blue')
得到 {'red','green','blue'}
colors.size //獲取set數(shù)組的長(zhǎng)度
得到 //3
colors.delete("red") //刪除元素
得到 //true colors里red就刪除了
colors.has('5') //檢查這個(gè)元素是否存在
得到 //true
colors.clear() //清空所有元素
把這個(gè)數(shù)組的元素給清空了
Set去重 轉(zhuǎn)換成數(shù)組
const numbers = [1,2,3,4,5,5,5,5,5,5]
const numbersSet = new Set(numbers)
const uniqueNumbers = [...numbersSet]
WeakSet
WeakSet的元素只能是對(duì)象
不能for of forEach .size .clear
會(huì)有自動(dòng)清除機(jī)制
let jelly = {name: 'jelly',age:'20'}
let mary = {name: 'mary ',age:'25'}
const weakPeple = new weakSet([jelly,mary])
consolo.log(weakPeple)
mary = null //這里刪除了mary
consolo.log(weakPeple) //但是普通數(shù)組方法這里還是會(huì)打印出來(lái) 就是[內(nèi)存泄露] 所以用WeakSet
使用情況:
屬性只能是對(duì)象的時(shí)候
數(shù)據(jù)不可用之后 希望集合當(dāng)中的 相關(guān)的 引用和數(shù)據(jù)會(huì)被自動(dòng)回收 以達(dá)到一個(gè)內(nèi)存優(yōu)化的目的
Map 鍵值對(duì)集合類(lèi)型
鍵(key)可以是任意類(lèi)型的數(shù)據(jù)比如對(duì)象{},3 屬性可以是任意類(lèi)型的數(shù)據(jù)
可以遍歷 for of forEach
唯一的對(duì)象 元素不會(huì)有重復(fù)的存在 重復(fù)時(shí)會(huì)忽略
const people = new Map([['apple,',6],['banana',5]]) //數(shù)組中 的相對(duì)應(yīng) 數(shù)組
people.set('jelly',23)
people.set('mary',25)
people.set('miffy',30) //添加新的元素
得到// {'jelly':23,'mary':25,'miffy':30}
people.get('jelly') //輸入key獲得相對(duì)應(yīng)的value
得到 // 23
people.size //獲取鍵(key)值(value)對(duì)的數(shù)量
得到// 3
people..has('jelly') 檢查這個(gè)屬性是否存在
得到// true
people.delete("mary") 刪除元素
得到// true 數(shù)組相應(yīng)鍵值對(duì)刪除
people.clear 清空所有元素
得到//清空所有元素鍵值對(duì)的對(duì)象
使用情況:
當(dāng)你想要存儲(chǔ)關(guān)于這個(gè)對(duì)象的信息 而不是把這個(gè)信息存儲(chǔ)在這個(gè)對(duì)象上的時(shí)候 使用map來(lái)操作
WeakMap
WeakMap的key只能是對(duì)象
不能for of forEach .size .clear
會(huì)有自動(dòng)清除功能 如果這個(gè)對(duì)象在其他地方?jīng)]有引用的話 就會(huì)自動(dòng)清除
let jelly = {name: 'jelly'}
let miffy = {name: 'miffy'}
const weak = new WeakMap()
weak.set(miffy,'miffy is the 2nd best!')
jelly = null
miffy = null
使用情況:
屬性只能是對(duì)象的時(shí)候
數(shù)據(jù)不可用之后 希望集合當(dāng)中的 相關(guān)的 引用和數(shù)據(jù)會(huì)被自動(dòng)回收 以達(dá)到一個(gè)內(nèi)存優(yōu)化的目的