天天看點

es6基礎 --- 7、Set Map SymbolSetMapSymbol

Set

與Array類似,隻是其元素是不能重複的。周遊可用forEach  for of

const s1 = new Set([1,2,3,3]) // 初始化 1 2 3
		const s = new Set(); // 初始化
		s.add(1).add(2).add(1); // 1 2
		s.size; // 2
		s.has(1) // true
		s.delete(3) // false
		s.clear()
           
  • 實際使用場景
// 數組去重, 利用Set特性及展開符或者Array.from
		const arr = [1,2,3,2,4,3,5]
		const newArr = [...new Set(arr)]
		const newArr1 = Array.from(new Set(arr))
           

Map

與對象類似,是鍵值對集合,但對象的鍵隻能為string或者symbol,如果不是string,也會調用toString()方法轉化為string,。Map的“鍵”的範圍不限于字元串,各種類型的值(包括對象)都可以當作鍵。

const m = new Map()
		const tom = { name : 'tom'}
		m.set(tom, 90)
		m.get(tom) // 90
		m.has(tom) // true
		m.delete(tom) // true
		m.clear()
           

Symbol

一個獨一無二的值。

const sym = Symbol() // 生成一個獨一無二的值
		typeof sym // symbol
           
  • 實踐
// 實作私有變量
		const obj ={
			[sym] : 'tt',
			say() {
				console.log(this[sym])
			}
		}
		// 添加獨一無二的對象鍵值,防止沖突
		const obj1 = {
			[Symbol('foo')] : 1,
			[Symbol('foo')] : 2
		}
           
  • 周遊

in Object.keys() Json.stringfy()都會忽略對象鍵值為symbol的屬性

Object.getOwnPropertySymbols()

方法,可以擷取指定對象的所有 Symbol 屬性名。該方法傳回一個數組,成員是目前對象的所有用作屬性名的 Symbol 值。

es6