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

Electron开发中如何基于用户输入动态生成变量与执行代码

实现方案

1. 动态存储用户输入的实现

不建议单独生成string_1、string_2这类离散变量,后续维护难度很高,优先推荐用数组存储所有输入内容,同时也可以兼容你要的带序号变量需求:

  • 全局初始化存储变量:
// 渲染进程全局作用域下初始化
// 方案1:用数组存储,更便于后续遍历
const userInputList = []

// 每次用户输入完成后执行
function saveUserInput(inputValue) {
  userInputList.push(inputValue)
  // 如果你需要生成指定格式的带序号变量,直接挂载到全局window对象即可
  window[`string_${userInputList.length}`] = inputValue
  // 第一次输入后可直接访问 string_1,第二次输入后可访问 string_2,以此类推
}

2. 按钮点击批量执行逻辑实现

直接遍历存储的输入内容即可生成你要的try/catch执行逻辑,无需手动拼接代码:

// 绑定按钮点击事件
document.querySelector('#你的按钮ID').addEventListener('click', () => {
  // 遍历所有存储的用户输入
  userInputList.forEach((inputStr, index) => {
    try {
      // 替换为你实际要调用的业务函数名,注意不要用function作为函数名,属于JS保留关键字
      你的业务函数(inputStr)
      // 如果你要用之前生成的string_xxx变量,也可以写成:你的业务函数(window[`string_${index+1}`])
    } catch (error) {
      console.log(error)
    }
  })
})

如果你需要生成可导出的代码字符串而非直接运行,可以用以下方法拼接得到你要的格式:

function getExecCodeString() {
  let resultCode = ''
  userInputList.forEach((_, index) => {
    const variableName = `string_${index + 1}`
    resultCode += `try{
  你的业务函数('${variableName}');
}
catch (error)
  console.log(error);\n\n`
  })
  // 输出的resultCode就是符合你要求格式的代码字符串
  return resultCode
}

内容的提问来源于stack exchange,提问作者Rohaan Patel-Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:15:03