這是一種不允許值重復(fù)的順序數(shù)據(jù)結(jié)構(gòu)
描述
集合是由一組無(wú)序且唯一(即不能重復(fù))的項(xiàng)組成的
這個(gè)數(shù)據(jù)結(jié)構(gòu)使用了與有限集合相同的數(shù)學(xué)概念
創(chuàng)建
使用對(duì)象表示集合
class Set {
constructor() {
this.items = {}
}
/**
* @description 使用 hasOwnProperty 方法
* @param {*} value
*/
has(value) {
return this.items.hasOwnProperty(value)
}
add(value) {
if (this.has(value)) {
return false
} else {
this.items[value] = value
return true
}
}
remove(value) {
if (!this.has(value)) {
return false
} else {
delete this.items[value]
return true
}
}
clear() {
this.items = {}
}
size() {
let count = 0
for (let key in this.items) {
if (this.items.hasOwnProperty(key))
++count
}
return count
}
values() {
let values = []
for (let key in this.items) {
if (this.items.hasOwnProperty(key)) {
values.push(this.items[key])
}
}
return values
}
}
方法的實(shí)現(xiàn)
has(value) 方法
/**
* @description 使用 hasOwnProperty 方法
* @param {*} value
*/
has(value) {
return this.items.hasOwnProperty(value)
}
/**
* @description 使用 in 操作符
* @param {*} value
*/
has(value) {
return value in this.items
}
size() 方法
// 遍歷對(duì)象的所有屬性
size() {
let count = 0
for (let key in this.items) {
if (items.hasOwnProperty(key)) // 檢查他們是否是對(duì)象自身的屬性
++count
}
return count
}
注意
- 不能簡(jiǎn)單地使用 for-in 語(yǔ)句遍歷 items 對(duì)象的屬性,并遞增 count 變量的值。還需要使用 hasOwnProperty 方法(以驗(yàn)證 items 對(duì)象具有該屬性),因?yàn)閷?duì)象的原型包含了額外的屬性(屬性既有繼承自 JavaScript 的 Object 類(lèi)的,也有術(shù)語(yǔ)對(duì)象自身,未用于數(shù)據(jù)結(jié)構(gòu))