数组-集合-字典是几乎编程语言都会默认提供的数据类型.(字典是一种以键-值对形式存储数据的数据结构)
在JavaScript中默认提供了数组, 但没有提供集合和字典(ES6中增加了set,map), 现在我们基于对象实现一下字典.
dictionary类的基础是Array类,而不是Object类,因为要对字典中的键排序,而对象的属性不能排序,所以基于Array,但是不要忘记了,js中一切皆对象,数组也是对象。
// 字典是一种以键-值对形式存储数据的数据结构
function Dictionary () {
this.dataStore = []
}
Dictionary.prototype = {
constructor: Dictionary,
add: function (key, value) {
this.dataStore[key] = value
},
find: function (key) {
return this.dataStore[key]
},
remove: function (key) {
// delete函数是object类的一部分,使用对键的引用作为参数,可以同时上传键和与其关联的值
delete this.dataStore[key]
},
showAll: function () {
// 当键的类型为字符串时,length属性就不管用了,因为数组也是对象,所以采用Object.keys()转换成有长度的数组
Object.keys(this.dataStore).forEach(function (key) {
console.log(key + '->' + this.dataStore[key])
}, this)
// 这里要把this传进来,不然function里的this指向会有问题
},
count: function () {
return Object.keys(this.dataStore).length
},
clear: function () {
// 这里采用另一种for in 遍历
// for in 遍历主要用的对象属性的遍历,这里因为键的类型为字符串,所以可以采用for in
for (var key in this.dataStore) {
delete this.dataStore[key]
}
}
}
// 使用
var book = new Dictionary()
book.add('book1', '100')
book.add('book2', '200')
book.add('book3', '300')
book.add('book4', '400')
book.showAll()
var count1 = book.count()
console.log(count1)
console.log('-----------------------------')
var findBook = book.find('book1')
console.log(findBook)
console.log('-----------------------------')
book.remove('book1')
book.showAll()
var count2 = book.count()
console.log(count2)
book.clear()
var count3 = book.count()
console.log(count3)