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

JavaScript if/else分支异常:rowIndex条件下仅后段代码生效问题求助

问题排查
  • 多值匹配语法错误:JS中if (rowIndex == 1,2,3,4,5)的写法实际是逗号运算符,最终仅会判断rowIndex == 5,完全不符合需求。判断变量是否属于某几个值,应该用[1,2,3,4,5].includes(rowIndex)的写法。
  • 分支结构语法错误:else后不能直接跟判断条件,需要使用else if才可以接后续判断逻辑;同时第一个if代码块缺少闭合的},导致分支逻辑嵌套完全混乱,这就是保留两段代码时仅执行第二部分的核心原因。
  • 变量作用域错误:roundedRT在第一个if块内声明,第二个分支直接调用会触发未定义报错,需要把公共变量的声明提到两个分支外面。
  • 符号缺失错误:代码中多处缺少}、)等闭合符号,会直接触发语法解析失败。
修正后完整代码
gorillaTaskBuilder.onScreenStart((spreadsheet: any, rowIndex: number, screenIndex: number, row: any, container: string) => {
    $('body').css('background-color', BACKGROUND_COLOUR);
    $('h1, h2, h3, h4, h5, p, span').css('color', TEXT_COLOUR);
    if (row.display == _requiredFeedbackDisplay) {
        if (screenIndex == _requiredFeedbackScreen) {
            // 公共逻辑提前,避免重复声明
            const lastRT: number = gorilla.retrieve(_RTKey, null, false);
            const roundedRT: number = Math.round(lastRT);
            let points: number;
            let metricName: string;
            
            if ([1,2,3,4,5].includes(rowIndex)) {
                points = 8000 - roundedRT;
                metricName = 'pointConvertedBlue';
            } else if ([6,7,8,9,10].includes(rowIndex)) {
                points = 1500 - roundedRT;
                metricName = 'pointConvertedRed';
            } else {
                // 可根据需求补充其他rowIndex的处理逻辑
                return;
            }
            
            // 公共渲染逻辑统一处理
            $(container + _requiredFeedbackZoneSelector).html(`<h1><p style="color: white;">You earned ${points} points</p></h1>`);
            gorilla.refreshLayout();
            gorilla.metric({
                trial_number: metricName,
                response: points
            });
        }
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 07:00:02