JavaScript字符,单词和空格计数函数

javascript character, word, & space count function

本文关键字:函数 空格 字符 单词 JavaScript      更新时间:2023-09-26

>我正在尝试创建一个javascript函数,该函数计算字符串中的字符,单词,空格和平均单词长度,并在单个对象中返回它们。最初我让字符计数工作,但是当添加字数时,我迷路了。我可以声明一个包含其他函数的单个函数来执行此操作吗?另外,我似乎无法让前 2 部分正常工作,但我不确定这段代码有什么问题:

var charLength = 0;
var count = function(text) {
  var charLength = text.length;
  return charLength;
};
var wordCount = 0;
for (i = 1; i < text.length; i++) {
  if (text.charAt(i) == " ") {
    wordCount++;
  }
  return wordCount + 1;
  console.log("Characters: " + charLength + " Words: " + wordCount);
}
var text = "Hello there fine sir.";
count(text);

这是jsFiddle:https://jsfiddle.net/minditorrey/z9nwhrga/1/

目前你有混合的函数和非函数。我想你的意思是将单词计数包含在count中,但目前它存在于那里之外。但是,将该代码直接移动到count中会很麻烦,因为函数中不能有多个 return 语句。您需要跟踪局部变量中的测量值,然后构造包含所有值的内容。像这样,例如:

//var charLength = 0; You have a global and local variable, omit this one
var count = function(text) {
  var charLength = text.length;
  var wordCount = 0;
  for (var i = 0; i < text.length; i++) { // declare i with var, start at 0
    if (text.charAt(i) == " ") {
      wordCount++;
    }
  }
  return { 'charLength': charLength, 'wordCount': wordCount };
};
var text = "Hello there fine sir.";
console.log(count(text)); // add a way to see the results

为了更进一步,您可以将字数统计简化为:

text.split(' ').length

因此,您的新count函数如下所示:

var count = function(text) {
  var charLength = text.length;
  var wordCount = text.split(' ').length;
  return { 'charLength': charLength, 'wordCount': wordCount };
};

我已经更新了你的小提琴:

function goforit(text){
  var charLength = text.length;
  var spacesCount = 0;
  for (i = 1; i < text.length; i++) {
    if (text.charAt(i) == " ") {
      spacesCount++;
    }
  }
  var wordsArray = text.split(" ");
  var totalWordLen=0;
  for (j = 0; j < wordsArray.length; j++) {
    totalWordLen = totalWordLen + wordsArray[j].length;
  }  
  var wordCount = spacesCount+1;
  var average = totalWordLen / wordsArray.length;
  var outputString = "Characters: " + charLength + " Words: " + wordCount + " Spaces: " + spacesCount + " Average: " + average;
    alert(outputString)
  console.log(outputString);
}

var text = "Hello there fine sir.";
goforit(text);

检查这个(或在jsbin:https://jsbin.com/tazayaqige/edit?js,console(:

var count = function(text) {
  var charLength = text.length;
  var wordCount = text.split(" ").length;
  console.log("Characters: " + charLength + " Words: " + wordCount);
  return { wordCount: wordCount, charLength: charLength };
}
var text = "Hello there fine sir.";
count(text);

正在尝试定义两个函数,但实际上您定义了count函数,但另一个wordCount并未定义为函数。只是语句,并且有一个返回语句等。无论如何,检查上面的代码,它应该可以解决问题。

您需要

将其设为类,请参阅有关如何执行此操作的链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

一旦你有一个类,就删除了 return 语句,并使变量成为类的全局变量。这是你可以调用类名,然后拉出显示所需的变量。

您可以通过多种方式获得字数统计。就个人而言,我会使用 str.split(' '(.length;如果您然后将其分配给一个变量,您将能够循环访问它,收集有关单词长度的统计信息并得出您的平均值等。