You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS自制编程语言标签计数异常求助:.includes无法统计重复标签

解决自制编程语言重复标签未触发语法错误的问题

问题根源在于原代码使用includes()仅检测标签是否存在,无法统计重复出现的次数,导致ClassTagAmount计算逻辑失效。要解决这个问题,需要替换检测方式为统计标签出现的总次数,再通过开始标签与结束标签的数量差判断是否存在语法错误。

修改核心逻辑

将原有的存在性检测改为数量统计:

  • 使用正则表达式的match()方法匹配所有目标标签,通过返回数组的长度获取标签出现次数
  • 计算ClassTagAmount = 开始标签数量 - 结束标签数量,若结果不等于0则抛出语法错误

修改后的完整代码示例

HTML

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>自制编程语言编译器</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <textarea id="codeInput" placeholder="输入你的代码..."></textarea>
    <button onclick="Compile()">编译</button>
    <div id="errorOutput"></div>
    <script src="compiler.js"></script>
</body>
</html>

CSS

#codeInput {
    width: 80%;
    height: 200px;
    margin: 10px;
    padding: 10px;
}
button {
    margin: 0 10px;
    padding: 8px 16px;
}
#errorOutput {
    margin: 10px;
    color: red;
    font-weight: bold;
}

JavaScript

function Compile() {
    const code = document.getElementById('codeInput').value;
    const errorOutput = document.getElementById('errorOutput');
    errorOutput.textContent = '';

    // 统计开始标签和结束标签的数量
    const classStartCount = code.match(/Main Anim\[\] class=>/g)?.length || 0;
    const classEndCount = code.match(/<=ClassEnd/g)?.length || 0;
    const ClassTagAmount = classStartCount - classEndCount;

    // 判断标签数量是否匹配
    if (ClassTagAmount !== 0) {
        errorOutput.textContent = `语法错误:类标签不匹配,存在${ClassTagAmount > 0 ? '多余的开始标签' : '多余的结束标签'}`;
        return;
    }

    // 其他编译逻辑...
    errorOutput.textContent = '编译成功!';
}

说明

  • match(/Main Anim\[\] class=>/g)会返回所有匹配的开始标签数组,?.length || 0处理无匹配时的undefined情况,确保计数为0
  • 通过计算数量差,无论是多个开始标签还是多个结束标签,都能准确检测并抛出错误
  • 示例中当输入两个Main Anim[] class=>和一个<=ClassEnd时,ClassTagAmount为1,会触发"多余的开始标签"错误提示

内容的提问来源于stack exchange,提问作者GMD Gooodsoups

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 21:15:13