es6基礎 --- 7、Set Map Symbol

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 值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章