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

在jsPsych(JavaScript)实验中实现分支逻辑遇问题求助

解决方案

核心问题有两个:

  1. 代码执行时机错误:初始化timeline时就尝试获取consent试次的response,但此时consent试次还未运行,无数据可获取。jsPsych的timeline是异步执行的,不能在初始化阶段同步获取未完成试次的数据。
  2. 数据获取方式错误:jsPsych.data.get().last(1).select('response')返回的是jsPsych数据对象,而非原始response值,因此会显示[object Object],也无法直接与字符串比较。

正确实现分支的两种方法

方法一:使用conditional_function(推荐)

在timeline中添加条件节点,通过conditional_function动态判断之前的试次数据,决定加载哪个提示:

// 同意后的提示试次
var consented_msg = {
  type: jsPsychHtmlKeyboardResponse,
  stimulus: 'You consented!',
  choices: [' '],
  data: {task: 'Instruction'},
};

// 不同意后的提示试次
var not_consented_msg = {
  type: jsPsychHtmlKeyboardResponse,
  stimulus: 'You did not consent!',
  choices: [' '],
  data: {task: 'Instruction'},
};

// 条件分支节点
var consent_branch = {
  type: jsPsychHtmlButtonResponse,
  stimulus: '',
  choices: [],
  conditional_function: function() {
    // 获取最后一个试次的response值(数字类型,0为同意,1为不同意)
    var response = jsPsych.data.get().last(1).values()[0].response;
    // 根据选择跳转对应提示
    if (response === 0) {
      jsPsych.run([consented_msg]);
    } else {
      jsPsych.run([not_consented_msg]);
    }
    return false; // 返回false,不执行当前空节点
  }
};

// 构建timeline
timeline.push(consent);
timeline.push(consent_branch);

方法二:使用试次的on_finish回调

在consent试次的on_finish回调中,根据用户选择直接将对应提示添加到timeline:

var consent = {
  type: jsPsychHtmlButtonResponse,
  stimulus: 'Consent Information',
  choices: ['I consent to participanting<br>in this study', 
            'I do not consent to participating<br>in this study'],
  render_on_canvas:false,
  data: {task: 'Consent'},
  on_finish: function(data) {
    // data.response为用户选择的按钮索引(0或1,数字类型)
    var msg_trial = data.response === 0 
      ? {
          type: jsPsychHtmlKeyboardResponse,
          stimulus: 'You consented!',
          choices: [' '],
          data: {task: 'Instruction'},
        }
      : {
          type: jsPsychHtmlKeyboardResponse,
          stimulus: 'You did not consent!',
          choices: [' '],
          data: {task: 'Instruction'},
        };
    // 将提示试次添加到timeline末尾并继续执行
    jsPsych.addNodeToEndOfTimeline(msg_trial);
  }
}

// 仅需将consent添加到timeline
timeline.push(consent);

关键注意点

  • jsPsychHtmlButtonResponse的response返回数字类型的按钮索引(第一个按钮为0,第二个为1),判断时需用=== 0而非=== '0'。
  • 不可在timeline初始化阶段获取未运行试次的数据,必须在试次完成后的回调(如on_finish)或条件函数中获取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 18:27:04