使用javascript计算短语中每个单词的出现次数

Count the occurrence of each word in a phrase using javascript(使用javascript计算短语中每个单词的出现次数)
本文介绍了使用javascript计算短语中每个单词的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如对于输入olly olly in come free"

程序应该返回:

olly: 2在:1来:1免费:1

测试写成:

var words = require('./word-count');

describe("words()", function() {
  it("counts one word", function() {
    var expectedCounts = { word: 1 };
    expect(words("word")).toEqual(expectedCounts);
  });

//more tests here
});

  1. 如何从我的 word-count.js 文件开始?创建一个方法 words() 或一个模块 Words() 并在其中创建一个 expectedCount 方法并导出它?

  1. How do I start in my word-count.js file? Create a method words() or a module Words() and make an expectedCount method in there and export it?

我将字符串视为数组还是对象?在对象的情况下,我如何开始将它们分解成单词并迭代计数?

Do I treat the string as an array or an object? In the case of objects, how do I start breaking them into words and iterate for the count?

推荐答案

function count(str) {
  var obj = {};
  
  str.split(" ").forEach(function(el, i, arr) {
    obj[el] = obj[el] ? ++obj[el] : 1;
  });
  
  return obj;
}

console.log(count("olly olly in come free"));

这段代码应该能得到你想要的.
为了更好地理解代码,我建议您通过数组原型函数和字符串原型函数.
为了简单了解我在这里做什么:

This code should get just what you want.
For more understanding on the code I would advice you to go through array prototype functions and string prototype functions.
For simple understanding of what I`m doing here:

  1. 创建一个计数函数,该函数返回一个计数所有单词出现次数的对象.
  2. 使用 split(" ") 根据提供数组的空格分割字符串.
  3. 使用 forEach 方法遍历 spitted 数组中的所有元素.
  4. 三元运算符 :? 检查值是否已经存在,是否加一或赋值为 1.
  1. Create a count function which returns an object of count of all occurrences of words.
  2. Split the string using split(" ") based on a space which gives an array.
  3. Use forEach method to iterate through all the elements in the spitted array.
  4. Ternary operator :? to check if value already exists, if it does increment by one or assign it to 1.

Array.prototypeString.prototype

这篇关于使用javascript计算短语中每个单词的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)