计算javascript中的单词并将其推入对象 [英] Counting words in javascript and push it into an object

查看:90
本文介绍了计算javascript中的单词并将其推入对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个javascript程序,通过单词计算并返回单词及其出现的次数,例如{hello:2,@ hello:1,world:1,toString:1}

I want to achieve a javascript program that count through a word and return the word and the number of times it appears eg {hello : 2, "@hello":1, world : 1, toString:1}

下面是我的代码,但我只得到总字数

below is my code but i only get the total number of words

function words(str) { 
    app = {};
    return str.split(" ").length;
}

console.log(words("hello world"));   


推荐答案

使用reduce来迭代单词数组,并计算实例:

Use reduce to iterate the words array, and count the instances:

function words(str) { 
    return str.split(" ").reduce(function(count, word) {
      count[word] = count.hasOwnProperty(word) ? count[word] + 1 : 1;
      
      return count;
    }, {});
}

console.log(words("reserved words like prototype and toString ok? Yes toString is fine"));

这篇关于计算javascript中的单词并将其推入对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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