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

JavaScript中实现记录最后修改布尔变量并切换前值的方法

实现布尔变量切换与记录最后修改变量的方案

核心需求

维护多个布尔变量,用单独变量记录最后被修改的变量名称;每次修改新布尔变量时,先切换此前记录的那个变量的状态,再更新当前变量状态与记录的变量名。

原代码问题分析

原代码中lastChangedBooleanVariable存储的是变量的值(this.isDemo3的结果是true),而非变量名称字符串,导致无法通过它定位到之前的变量进行状态切换。

实现思路与代码示例

关键调整点

  • 用字符串类型存储最后修改的变量名称,而非变量值
  • 处理新变量时,通过字符串访问对象属性的方式,切换之前变量的状态
  • 更新当前变量状态后,同步更新记录的变量名

TypeScript 代码实现

// 初始化布尔变量
isDemo1 = false;
isDemo2 = false;
isDemo3 = true;
isDemo4 = false;
isDemo5 = false;

// 存储最后修改的变量名称(初始值对应已激活的isDemo3)
lastChangedBooleanVariable: string = 'isDemo3';

handleBooleanVariables(currentChangedVariable: string) {
    // 校验变量是否存在,避免无效操作
    if (!(currentChangedVariable in this)) {
        console.error(`不存在变量:${currentChangedVariable}`);
        return;
    }

    // 1. 切换上一个修改的变量状态
    if (this.lastChangedBooleanVariable) {
        this[this.lastChangedBooleanVariable] = !this[this.lastChangedBooleanVariable];
    }

    // 2. 切换当前变量状态(若需设置为指定值,直接赋值即可,比如 this[currentChangedVariable] = true;)
    this[currentChangedVariable] = !this[currentChangedVariable];

    // 3. 更新最后修改的变量名称记录
    this.lastChangedBooleanVariable = currentChangedVariable;
}

补充说明

  • 如果需求是将当前变量设置为固定值(而非切换),只需把第二步的切换逻辑改为直接赋值,例如this[currentChangedVariable] = true;
  • 若变量数量较多,可考虑将布尔变量统一放在一个对象中管理,比如demoFlags: { isDemo1: boolean; ... },这样属性访问会更清晰,也便于批量维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:05:42