【问题标题】:How can I count these words, using script in google sheets?我如何计算这些单词,使用谷歌表格中的脚本?
【发布时间】:2020-02-05 21:24:33
【问题描述】:

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

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;
}

【问题讨论】:

  • 欢迎。请共享您的电子表格副本,不包括私人或机密数据。您是否还可以编辑您的问题以包含您收到的 exact 错误消息 - “_google 表格给我一个错误,他无法处理表达式:...因为某处有 null”没有告诉我们错误的性质。

标签: javascript google-sheets formula counting


【解决方案1】:

正如 Tedinoz 所说,如果您可以共享电子表格,则提供具体帮助会更容易。

但与此同时,这里有两个 sn-ps 帮助解释如何获取较长字符串中单词的计数。

示例 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.

【讨论】:

    猜你喜欢
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多