字典是一种以键-值对的形式存储数据的数据结构,接下来我们将使用JavaScript实现字典数据结构。
1、定义字典类
由于比较字典数据结构比较简单,就直接上代码好了。
class Dictionary {
constructor () {
this.data = []
}
}
2、add()
此方法用于往字典添加元素,需要接受两个参数,键和值
add (key, value) {
this.data[key] = value
}
3、find()
此方法用于通过查找key值返回对应的value
find (key) {
return this.data[key]
}
4、remove()
此方法用于删除字典中的键值对(借助JavaScript的delete()函数)
remove (key) {
delete this.data[key]
}
5、showAll()
此方法用于显示所有键值对
showAll () {
for(let key in this.data) {
console.log(key + '->' + this.data[key])
}
}
6、count()
此方法用于返回字典中元素的个数,方法中不可以使用length,因为key为字符串的话,length属性失效,比如let arr = []; arr['one'] = 1; arr['two'] = 2;console.log(arr.length)
;输出为0。
count () {
let n = 0
for (let key in this.data) {
n++
}
console.log(n)
}
7、pSort()
此方法用于给字典排序,通过排序字典的key即可实现
pSort () {
const keySort = Object.keys(this.data).sort()
for (let i = 0; i < keySort.length; i++) {
console.log(keySort[i] + '->' + this.data[keySort[i]])
}
}
8、clear()
此方法用于清空字典
clear () {
for (let key in this.data) {
delete this.data[key]
}
}
9、测试实例
let dic = new Dictionary()
dic.add('Candy', 999)
dic.add('Allen', 666)
dic.add('Scott', 777)
dic.add('Tom', 555)
dic.add('Jack', 333)
console.log('字典中的元素有:')
dic.showAll()
console.log('字典中Tom的值为:')
dic.find('Tom')
console.log('字典中的元素个数为:')
dic.count()
console.log('移除字典中key为Jack的元素后的剩余的元素:')
dic.remove('Jack')
dic.showAll()
console.log('按key排序:')
dic.pSort()
console.log('开始清除所有元素')
dic.clear()
console.log('清除后字典中元素个数为')
dic.count()
10、运行结果
使用node环境运行此js文件,node dictionary.js
,可见输出如下:
11、完整源码
class Dictionary {
constructor () {
this.data = []
}
add (key, value) {
this.data[key] = value
}
find (key) {
return this.data[key]
}
remove (key) {
delete this.data[key]
}
showAll () {
for(let key in this.data) {
console.log(key + '->' + this.data[key])
}
}
count () {
let n = 0
for (let key in this.data) {
n++
}
console.log(n)
}
pSort () {
const keySort = Object.keys(this.data).sort()
for (let i = 0; i < keySort.length; i++) {
console.log(keySort[i] + '->' + this.data[keySort[i]])
}
}
clear () {
for (let key in this.data) {
delete this.data[key]
}
}
}
let dic = new Dictionary()
dic.add('Candy', 999)
dic.add('Allen', 666)
dic.add('Scott', 777)
dic.add('Tom', 555)
dic.add('Jack', 333)
console.log('字典中的元素有:')
dic.showAll()
console.log('字典中Tom的值为:')
dic.find('Tom')
console.log('字典中的元素个数为:')
dic.count()
console.log('移除字典中key为Jack的元素后的剩余的元素:')
dic.remove('Jack')
dic.showAll()
console.log('按key排序:')
dic.pSort()
console.log('开始清除所有元素')
dic.clear()
console.log('清除后字典中元素个数为')
dic.count()
《JavaScript算法与数据结构——字典实现》完结,有错误欢迎指出,五一快乐~
最后
以上就是温柔小伙最近收集整理的关于JavaScript算法与数据结构——字典详解的全部内容,更多相关JavaScript算法与数据结构——字典详解内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复