javascript - 如何从字符串计算数组元素的计数
问题描述
const operators = ["+", "-", "/", "*", "%"];
var string = "2+2-3"
这里计数将等于 2
我需要计算字符串中使用的运算符总数
解决方案
你需要:
- 在每个字符上拆分字符串
.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)
推荐阅读
- node.js - 如何编写中间件来修改节点js中的响应
- c# - Unity 如何通过 C# 脚本更改 Unity 的 3D 对象参数
- javascript - 如何更改多个数组对象的索引?
- kotlin - Kotlin flatten + 嵌套对象的映射
- java - Java ME 或 Java SE(Raspberry Pi 零)
- java - 为什么引用在内存中有大小,即使它没有引用此代码示例中的对象?
- linux - 在 apropos 命令中计算单词
- reactjs - componentDidUpdate 比 setState 中的实际值落后一步
- typescript - 将 JSON 作为类型导入
- javascript - 如何在 Inputmask 插件中设置范围?