集合

作者: 林键燃 | 来源:发表于2019-03-11 10:04 被阅读0次

这是一种不允许值重复的顺序数据结构

描述

  • 集合是由一组无序且唯一(即不能重复)的项组成的

  • 这个数据结构使用了与有限集合相同的数学概念

创建

使用对象表示集合

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
    }
}

方法的实现

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() 方法

// 遍历对象的所有属性
size() {
    let count = 0 
    for (let key in this.items) {
        if (items.hasOwnProperty(key)) // 检查他们是否是对象自身的属性
            ++count
    } 
    return count
}

注意

  • 不能简单地使用 for-in 语句遍历 items 对象的属性,并递增 count 变量的值。还需要使用 hasOwnProperty 方法(以验证 items 对象具有该属性),因为对象的原型包含了额外的属性(属性既有继承自 JavaScript 的 Object 类的,也有术语对象自身,未用于数据结构)

相关文章

  • 我的Swift的学习总结 -->第二周

    集合 集合:Set,定义一个集合可以写成:var 集合名 : Set<集合类型> = [集合元素],具体的集合应用...

  • markdown 测试

    集合 集合 集合 引用

  • kotlin学习第五天:集合,高阶函数,Lambda表达式

    集合 list集合 list集合分为可变集合与不可变集合。由list of创建的集合为不可变集合,不能扩容,不能修...

  • kotlin练习 ---- 集合练习

    kotlin练习 - 集合练习 Set集合 Set集合创建 Set集合的使用 List集合 List集合创建 Li...

  • 集合总结

    集合 集合分为单列集合和双列集合两种: 一.单列集合: Collection是单列集合的顶级接口: 其中有三类集合...

  • 映射、元组、集合

    映射 元组 集合 集合之seq 集合之set 集合之map

  • 16.Collection集合

    主要内容: Collection 集合 迭代器 增强for List 集合 Set 集合 1,集合 集合是java...

  • 集合与有序集合

    集合分为有序集合 (zset) 和无序集合 (set), 一般无序集合也直接说成集合 无序集合 (set) 无序集...

  • python入坑第八天|集合

    好的,各位蛇友,我们今天来学习集合。 内容: 集合的创建 集合操作符号 集合的内置函数 集合的创建 集合用set(...

  • 集合框架

    集合框架的概念 集合:存放数据的容器 集合框架:java中,用于表示集合,以及操作集合的类和接口的统称 数组与集合...

网友评论

      本文标题:集合

      本文链接:https://www.haomeiwen.com/subject/pekvpqtx.html