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

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

问题描述

我试图建立一个JavaScript函数这将算在输入阵列中的每个单词出现的次数。

例如:

输入

  A = [一,助推器,助推器,构造,亚当,亚当,亚当,亚当]

输出:

 一:1
助推器:2
构造:1
亚当:4

输出应该是字典-的一致好评。

我是新来的JavaScript,我试图用字典。但是,对象有一个名为构造的属性,因此 CNT [构造] 似乎不起作用。

下面是我的code和结果是:

  VAR CNT = {};
的console.log(构造);对于(VAR I = 0; I<则为a.length ++ I)
{
    如果(!(一个[i]于CNT))
        CNT [一个由[i]] = 0;
    其他
        CNT [一个[I] + = 1;
}对于(CNT中的VAR项)
    的console.log(项目+:+ CNT [项目]);

结果:

您可以看到,加1 CNT的构造函数的字符串。


解决方案

 函数count(ARR){
  返回arr.reduce(功能(M,E){
    M [E] =(+ M [E] || 0)+1;回报米
  },{});
}

背后的想法是


  • 使用的减少的优雅

  • M [E] 使用转换为数字 + M [E] 来避免构造(或的toString )的问题

示范

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

Example :

Input

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

Output:

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

Output should be dict-alike.

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.

Here is my code and the result:

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]);

Result:

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
  },{});
}

The idea behind are

  • the use of reduce for elegance
  • the conversion of m[e] to a number using +m[e] to avoid the constructor (or toString) problem

Demonstration

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

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