【问题标题】:JS - Count the number of occurrences found in a string [closed]JS - 计算字符串中出现的次数[关闭]
【发布时间】:2023-01-28 02:23:36
【问题描述】:

我需要在字符串中找到出现的次数:

var string = 'hello, i am blue.';
var specialChar = [' ', '!', '@', '#', '$', '%', '?', '&', '*', '(', ')', '_', '+', '=', '.'];
specialChar.forEach(word => {
  string.includes(word) && count++
});
console.log(count);

但它不起作用。

【问题讨论】:

  • 您期望变量count 来自哪里?
  • 我已将您的代码转换为正在运行的演示,这也不起作用,因为您在使用它之前没有定义 count 变量。此外,我已将 alert() 转换为 console.log()
  • 唯一的问题是您忘记了var count = 0;(在 forEach 循环之外),尽管可以通过其他方式改进代码
  • 不仅有忘记定义count 的拼写错误,而且由于您的循环方式也存在逻辑错误。现在,它只会计算字符串中唯一特殊字符的数量,但您似乎正在寻找使用的特殊字符总数

标签: javascript


【解决方案1】:

您需要初始化 count 变量:

var string = 'hello, i am blue.';
var specialChar = [' ', '!', '@', '#', '$', '%', '?', '&', '*', '(', ')', '_', '+', '=', '.'];

let count = 0
specialChar.forEach(word => {
  string.includes(word) && count++
});

console.log(count);

结果是:2(字符串包含 ',' & '.')

【讨论】:

    【解决方案2】:

    您没有初始化 count 变量:

    let count = 0;
    
    const string = 'hello, i am blue.';
    const specialChar = [' ', '!', '@', '#', '$', '%', '?', '&', '*', '(', ')', '_', '+', '=', '.'];
    specialChar.forEach(word => {
      string.includes(word) && count++
    });
    console.log(count);

    另外,请注意,当值可以更改时,我已从 var 更改为 let,当它是一个常量值时,我已更改为 const

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-27
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      相关资源
      最近更新 更多