首页 > 解决方案 > 如何从字符串计算数组元素的计数

问题描述

const operators = ["+", "-", "/", "*", "%"];
var string = "2+2-3"

这里计数将等于 2

我需要计算字符串中使用的运算符总数

标签: javascriptarrays

解决方案


你需要:

  • 在每个字符上拆分字符串.split("")
  • 过滤以保留数组中的那些
  • 取结果的长度

const operators = ["+", "-", "/", "*", "%"];
var string = "2+2-3+6+6+6+6+6"

const nb_total = string.split("").filter(elt => operators.includes(elt)).length
console.log("Nb of operators", nb_total)

const nb_uni = operators.filter(elt => string.includes(elt)).length
console.log("Nb of unique operators", nb_uni)


推荐阅读