什么是字典?
字典就是一中以健-值对形式存储数据的数据结构,是的你没有猜错,js中的Object类就是依照字典来设计的(其实,我不知道你没有猜😄)
所以说这样子看来字典还是很简单的,现在我们来实现一个字典类:
class Dicitonary { constructor() { this.dataSource = []; } // find: 返回指定key的值 find(key) { return this.dataSource[key]; } // display:显示字典中所有的元素 display() { Object.keys(this.dataSource).forEach(function (key) { console.log(key + '----' + this.dataSource[key]) }, this); } // add:向字典中增加元素 add(key, value) { this.dataSource[key] = value; } // remove:删除指定key的元素 remove(key) { delete this.dataSource[key]; } // count:统计字典中元素的个数 count() { let n = 0; return (Object.keys(this.dataSource).forEach(function () { n++; }), n); } // clear:清空字典 clear() { Object.keys(this.dataSource).forEach(function (key) { delete this.dataSource[key]; }, this); } // sortDis:字典中的元素排序输出 sortDis() { Object.keys(this.dataSource).sort().forEach(function (key) { console.log(key + '----' + this.dataSource[key]) }, this) } } var dictionary = new Dicitonary(); dictionary.add('b', 'bb'); dictionary.add('c', 'cc'); dictionary.add('a', 'aa'); dictionary.display(); dictionary.sortDis();
没错,它就和看起来那么简单。