我正在研究频率计数器代码,其中我计算给定字符串中每个单词的频率。
我正在创建一个对象,并将每个单词都作为键,并将频率作为值以创建键值对。
function wordCount(str) {
tempStr = str.toUpperCase()
arr1 = tempStr.split(" ")
let frequencyConter1 = {}
for (let val of arr1) {
frequencyConter1[val] = (frequencyConter1[val] || 0) + 1
}
for (key in frequencyConter1) {
console.log(key, frequencyConter1[key])
}
}
wordCount("My name is Xyz 1991 He is Abc Is he allright")
1991 1
MY 1
NAME 1
IS 3
XYZ 1
HE 2
ABC 1
ALLRIGHT 1
为什么1991年的产量居首位?
应该在XYZ之后,对吗?
答案 0 :(得分:5)
JavaScript中的对象不保留遇到顺序,要保留键的插入顺序,请使用新的 Map 对象:
function wordCount(str) {
tempStr = str.toUpperCase();
arr1 = tempStr.split(" ");
let frequencyConter1 = new Map();
for (let val of arr1 ){
frequencyConter1.set(val, ((frequencyConter1.get(val) || 0) + 1) );
}
for( let [key, value] of frequencyConter1){
console.log(`${key} ${value}`);
}
}
wordCount("My name is Xyz 1991 He is Abc Is he allright")
注意:正如@Kaiido所述,从ES2015开始,在某些情况下,会在对象的键上施加顺序。顺序是整数,例如按升序排列的键,按插入顺序排列的普通键和按插入顺序排列的Symbols,但它不适用于所有迭代方法。