Javascript 使用谷歌表单中的脚本,我如何计算这些单词?

Javascript 使用谷歌表单中的脚本,我如何计算这些单词?,javascript,google-sheets,formula,counting,Javascript,Google Sheets,Formula,Counting,我想计算字符串中一个单词的出现次数,但Google Sheets给了我一个错误,它无法处理以下表达式: finalScores.push(preOutputTxt.match(nameArr[x])).length); 因为某处是空的。我怎样才能解决这个问题? 完整代码: /** * * * * @customFunction */ function scoreCounting(scores, names){ //---variables---// var sco

我想计算字符串中一个单词的出现次数,但Google Sheets给了我一个错误,它无法处理以下表达式:

finalScores.push(preOutputTxt.match(nameArr[x])).length);   
因为某处是空的。我怎样才能解决这个问题? 完整代码:

/**
*   
*   
* 
* @customFunction
*/

function scoreCounting(scores, names){
  //---variables---//
  var scoresArr = [];
  var preOutputTxt = "";
  var finalScores = [];
  var nameArr = [];
  //---------------//


  //---creating an array from names and scores (scores are in string type)---//
  for(var w = 0; w < scores.length; w ++){
    scoresArr.push(scores[w]);
  }
  for(var z = 0; z < names.length; z++){
    nameArr.push(names[z]);
  }
  //---------------------------------------//


  //---make one big string with names---//
  for(var y = 0; y < scoresArr.length; y++){
   preOutputTxt += scoresArr[y];
  }
  //----------------------------------------------//


  //---counting how many times score (a name) occur, basing on name given by nameArr[]---//
  for(var x = 0; x < nameArr.length; x++){ 
    finalScores.push(preOutputTxt.match(nameArr[x])).length); 
  }

  return finalScores;
}
/**
*   
*   
* 
*@customFunction
*/
函数记分计数(分数、名称){
//---变数---//
var Scoresar=[];
var preOutputTxt=“”;
var finalScores=[];
var nameArr=[];
//---------------//
//---从名称和分数创建数组(分数为字符串类型)---//
对于(var w=0;w
正如Tedinoz所提到的,如果您可以共享一个电子表格,那么提供特定帮助会更容易

但同时,这里有两个片段可以帮助解释如何获得较长字符串中的单词计数

示例1:如果使用名称作为输入的
match()
,则只会得到第一个匹配项

[这是因为该方法需要正则表达式。传递字符串(或将变量集传递给字符串)类似于不带修饰符的正则表达式。]

function example1() {
  var preOutputTxt = 'abcabcabc';
  var name  = 'abc';
  var output = preOutputTxt.match(name);
  Logger.log('Output is %s. Length is %s.', output, output.length);
}

// Output is [abc]. Length is 1.0.
示例2:但如果使用带有全局修饰符的正则表达式,则会得到所有匹配项

function example2() {
  var preOutputTxt = 'abcabcabc';
  var name  = 'abc';
  var re = new RegExp(name, 'g');
  Logger.log('Regular expression is %s', re);
  var output = preOutputTxt.match(re);
  Logger.log('Output is %s. Length is %s.', output, output.length);
}

// Regular expression is /abc/g
// Output is [abc, abc, abc]. Length is 3.0.

欢迎请共享您的电子表格副本,不包括私人或机密数据。您是否也可以编辑您的问题,以包含您收到的确切错误消息-“\u google sheets给了我一个错误,他无法处理表达式:……因为某处存在空值”没有告诉我们错误的性质。