本文详解如何在 jspsych 7.x 中正确实现基于被试响应的分支逻辑,重点解决“无法实时获取前序试次数据导致条件判断失效”的常见问题,并提供可复用的条件时间线(conditional timeline)方案。
本文详解如何在 jspsych 7.x 中正确实现基于被试响应的分支逻辑,重点解决“无法实时获取前序试次数据导致条件判断失效”的常见问题,并提供可复用的条件时间线(conditional timeline)方案。
在 jsPsych 实验开发中,分支逻辑(如知情同意后的路径分流)是高频需求。但初学者常陷入一个关键误区:在构建时间线(timeline)阶段就试图读取尚未发生的被试响应。正如问题代码所示,jsPsych.data.get().last(1).select('response') 被调用时,实验尚未运行,consent 试次根本未执行,因此返回空或无效对象(如 [object Object]),导致 if (consented == '0') 永远不成立,所有被试均落入 else 分支。
根本解法是放弃“静态预判”,改用 jsPsych 原生支持的 动态条件时间线(Conditional Timeline) —— 它在每次时间线节点执行前实时评估函数,确保能准确读取已记录的试次数据。
以下是优化后的完整示例代码:
// 初始化 jsPsychconst jsPsych = initJsPsych();// 主时间线数组const timeline = [];// 1. 知情同意试次const consentTrial = { type: jsPsychHtmlButtonResponse, stimulus: '<h3>知情同意书</h3><p>本研究已通过伦理审查。点击下方按钮表示您的选择:</p>', choices: ['我同意参与本研究', '我不同意参与本研究'], data: { task: 'consent' }, on_finish: function(data) { // 可选:显式标记响应值(便于调试) data.response_label = data.response === 0 ? 'consent' : 'no_consent'; }};timeline.push(consentTrial);// 2. 同意后显示的内容const consentedInstruction = { type: jsPsychHtmlKeyboardResponse, stimulus: '<h3>感谢您的同意!</h3><p>接下来将开始正式实验任务。</p>', choices: [' '], data: { task: 'post_consent' }};// 3. 未同意后显示的内容const notConsentedInstruction = { type: jsPsychHtmlKeyboardResponse, stimulus: '<h3>感谢您的关注</h3><p>您已退出本实验。如有疑问,请联系研究人员。</p>', choices: [' '], data: { task: 'exit' }};// 4. 构建条件时间线(关键!)// ✅ 使用 filter() 精准查找 consent 试次,避免 .last(1) 的不确定性const consentedTimeline = { timeline: [consentedInstruction], conditional_function: () => { const consentData = jsPsych.data.get().filter({ task: 'consent' }); if (consentData.count() === 0) return false; // 尚未完成 consent,跳过 return consentData.last().response === 0; // 注意:button response 是数字索引(0=左按钮) }};const notConsentedTimeline = { timeline: [notConsentedInstruction], conditional_function: () => { const consentData = jsPsych.data.get().filter({ task: 'consent' }); if (consentData.count() === 0) return false; return consentData.last().response !== 0; }};// 5. 将条件时间线加入主时间线timeline.push(consentedTimeline, notConsentedTimeline);// 启动实验jsPsych.run(timeline);
通过该方案,你不仅能可靠实现知情同意分流,还可将其模式迁移至任意条件跳转场景(如按反应时分组、按问卷得分进入不同任务模块等)。记住核心原则:分支逻辑必须延迟到数据真实产生之后执行,而非在时间线构建期硬编码判断。