词频计数,修复标准属性的错误 [英] Word Frequency Count, fix a bug with standard property

查看:22
本文介绍了词频计数,修复标准属性的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个 javascript 函数,它可以计算输入数组中每个单词的出现次数.

I'm trying to build a javascript function which would count the number of occurrences of each word in an input array.

示例:

输入

a=["a","booster","booster","constructor","adam","adam","adam","adam"]

输出:

"a":1
"booster":2
"constructor":1
"adam":4

输出应该像字典一样.

我是 javascript 新手,我尝试使用 dict.但是对象有一个叫做构造函数"的属性,所以 cnt["constructor"] 似乎不起作用.

I'm new to javascript and I tried to use a dict. But objects have a property called "constructor", so cnt["constructor"] seems not to work.

这是我的代码和结果:

var cnt={};
console.log("constructor");

for(var i=0;i<a.length;++i)
{
    if(! (a[i] in cnt))
        cnt[a[i]]=0;
    else
        cnt[a[i]]+=1;
}

for(var item in cnt)
    console.log(item+":"+cnt[item]);

结果:

可以看到cnt的构造函数中添加了1作为字符串.

You can see that 1 is added to constructor of cnt as a string.

推荐答案

function count(arr){
  return arr.reduce(function(m,e){
    m[e] = (+m[e]||0)+1; return m
  },{});
}

背后的想法是

  • 为了优雅而使用reduce
  • 使用 +m[e]m[e] 转换为数字以避免 constructor(或 toString) 问题
  • the use of reduce for elegance
  • the conversion of m[e] to a number using +m[e] to avoid the constructor (or toString) problem

演示

这篇关于词频计数,修复标准属性的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆