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

如何用JavaScript实现支持DUP、POP等操作的栈式单词机器模拟器

解决方案

实现思路

  • 基于栈结构存储操作数,逐行解析输入指令执行对应操作
  • 每一条输入字符串先按空格拆分得到独立指令集合
  • 执行指令前做边界校验,避免空栈执行POP/DUP、栈元素不足2个时执行加减等非法操作
  • 所有指令执行完成后,按需求取结果存入result数组

完整代码实现

export class App {
  test: string;
  input: string[];
  result: string[];

  constructor() {
    this.test = `Word Machine Emulator`;
    this.input = ['23 DUP 4 POP 5 DUP + DUP + -', "5 6 + -"];
    this.result = [];
  }

  ngOnInit(){
    // 遍历所有输入指令串
    for (const instructionStr of this.input) {
      const stack: number[] = [];
      const instructions = instructionStr.split(' ');
      
      for (const ins of instructions) {
        // 判断是否为数字
        if (/^\d+$/.test(ins)) {
          stack.push(Number(ins));
          continue;
        }

        switch(ins) {
          case 'POP':
            // 空栈校验,可根据题目要求补充错误处理
            if (stack.length < 1) break;
            stack.pop();
            break;
          case 'DUP':
            if (stack.length < 1) break;
            stack.push(stack[stack.length - 1]);
            break;
          case '+':
            if (stack.length < 2) break;
            const a = stack.pop()!;
            const b = stack.pop()!;
            stack.push(a + b);
            break;
          case '-':
            if (stack.length < 2) break;
            const num1 = stack.pop()!;
            const num2 = stack.pop()!;
            stack.push(num2 - num1);
            break;
          default:
            // 非法指令可自行补充错误处理
            break;
        }
      }
      // 示例要求返回栈顶元素,若需要返回整个栈可修改此处逻辑
      this.result.push(stack.length ? String(stack[stack.length - 1]) : '-1');
    }
  }
}

关键逻辑说明

  • 数字识别:用正则/^\d+$/匹配纯数字指令,转换为数值后压入栈
  • POP操作:直接调用数组pop()方法移除栈顶元素
  • DUP操作:获取数组最后一位元素,复制后压入栈顶
  • 减法操作:栈是后进先出结构,先弹出的是栈顶元素,后弹出的是前一位元素,相减时以后弹出的元素为被减数,避免结果错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 04:15:03