// 字典
function Dictionary() {
this.dataStore = new Array()
}
Dictionary.prototype = {
constructor: Dictionary,
// 添加元素
add: function (key, value) {
this.dataStore[key] = value
},
// 查找元素
find: function (key) {
return this.dataStore[key]
},
//删除元素
remove: function (key) {
let flag = false
if (delete this.dataStore[key]) {
flag = true
}
return flag
},
//显示所有元素
showAll: function () {
Object.keys(this.dataStore).forEach((key) => {
console.log(key + "-->" + this.dataStore[key])
})
},
// 计算数组长度
count: function () {
let count = 0
Object.keys(this.dataStore).forEach(() => {
count++
})
return count
},
// 清除所有元素
clear: function () {
Object.keys(this.dataStore).forEach((key) => {
delete this.dataStore[key]
})
},
}
// let pBook = new Dictionary()
// pBook.add("mike", "123")
// pBook.add("nike", "5555")
// pBook.showAll()
// console.log(pBook.count())
// console.log(pBook.clear())
// pBook.showAll()
// console.log(pBook.dataStore.length)
// 计算字符串单词出现次数并加入字典中
var str = "the brown fox jumped over the blue fox"
let dictionary = new Dictionary()
function countTimes(str, dictionary) {
let strArray = str.split(" ")
// console.log(strArray)
let newArr = countedTimes(strArray)
let keys = Object.keys(newArr)
keys.forEach((item) => {
dictionary.add(item, newArr[item])
})
}
countTimes(str, dictionary)
dictionary.showAll()
//
function countedTimes(arr) {
var countedNames = arr.reduce((newArr, key) => {
// 如果key已经存在新数组中,就让值+1
if (key in newArr) {
// 计算出现次数
newArr[key]++
} else {
newArr[key] = 1
}
return newArr
}, [])
return countedNames
}
js----字典实现
最新推荐文章于 2022-02-05 14:28:02 发布