JavaScript 实现有限状态机(FSM)的完整示例
作者:小括号时间:2026-10-31 17:54:09浏览:331
本文介绍如何在 JavaScript 中实现有限状态机(FSM),通过定义 FiniteStateMachine 类管理状态、事件及动作。内容涵盖状态初始化、转换规则添加及结束状态检测,并提供完整的代码示例,帮助开发者在前端交互、游戏逻辑或表单验证等场景中有效管理复杂状态流转。
有限状态机概述
有限状态机(Finite State Machine, FSM)是描述系统状态行为的数学模型,在前端开发中可用于管理复杂UI交互逻辑,例如游戏及表单验证场景。
JavaScript 实现代码
以下展示一个JavaScript实现有限状态机的示例:
class FiniteStateMachine {
constructor() {
this.handlers = {};
this.startState = null;
this.endStates = [];
this.currentState = null;
}
// 设置初始状态
setStartState(name) {
this.startState = name;
this.currentState = name;
}
// 添加状态转换处理器
addHandler(state, event, newState, action) {
if (!this.handlers[state]) {
this.handlers[state] = {};
}
this.handlers[state][event] = { newState, action };
}
// 设置结束状态
addEndState(state) {
this.endStates.push(state);
}
// 处理事件,进行状态转换
handleEvent(event) {
if (this.currentState === null) {
throw new Error('FiniteStateMachine has no start state.');
}
const handler = this.handlers[this.currentState][event];
if (!handler) {
throw new Error(`Cannot handle event ${event} in state ${this.currentState}.`);
}
// 执行状态转换前的动作
if (handler.action) {
handler.action();
}
// 进行状态转换
this.currentState = handler.newState;
// 检查是否到达结束状态
if (this.endStates.includes(this.currentState)) {
console.log('Reached an end state:', this.currentState);
}
}
}状态机使用示例
使用示例:
// 创建一个有限状态机实例
const fsm = new FiniteStateMachine();
// 设置初始状态为 'state1'
fsm.setStartState('state1');
// 添加状态转换处理器和动作
fsm.addHandler('state1', 'event1', 'state2', () => console.log('Moving from state1 to state2'));
fsm.addHandler('state2', 'event2', 'state3', () => console.log('Moving from state2 to state3'));
fsm.addHandler('state3', 'event3', 'state1', () => console.log('Moving from state3 to state1'));
// 设置结束状态(可选)
fsm.addEndState('state3');
// 处理事件,进行状态转换
fsm.handleEvent('event1'); // 输出: Moving from state1 to state2
fsm.handleEvent('event2'); // 输出: Moving from state2 to state3
fsm.handleEvent('event3'); // 输出: Moving from state3 to state1 和 Reached an end state: state1扩展与优化建议
该有限状态机实现可根据具体需求扩展优化,如增加状态、事件、动作或采用复杂数据结构存储状态转换规则。
关于JavaScript实现有限状态机的文章介绍至此,更多相关内容请搜索本站历史文章或浏览相关文章,感谢支持!
作者最新文章
JS语法错误会阻止加载吗?区分SyntaxError与资源加载失败
2026-11-05 16:08:46
JavaScript常见SyntaxError语法错误排查与修复方法
2026-11-05 13:58:44
JS中slice、substring和substr截取字符串的区别
2026-11-05 13:43:47
JS 转 TS 手动迁移最佳实践:从配置 tsconfig 到消除 any 类型
2026-11-05 11:53:32
为什么JS数组push后得到的是数字而不是数组?
2026-11-05 09:59:18
