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

学校JavaScript项目运行报SyntaxError: Unexpected identifier错误求助

问题根因

你遇到的SyntaxError: Unexpected identifier报错核心原因是:JavaScript中逻辑或的运算符是||,不是英文单词or。你所有if判断语句中写的or会被JS解析器识别为未声明的变量标识符,所以会在对应if语句的位置抛出该报错,这也是你注释掉一行if后其他if语句仍报相同错误的原因。

其他需要修复的代码问题

除了逻辑运算符错误外,你的代码还存在以下几处问题需要同步修正:

  • 逻辑判断逻辑错误:你现在两个if判断的条件完全一致,且温感阈值写反了,正常逻辑应该是温度≥50提示热,<50提示冷。
  • 函数调用参数不匹配:你定义convertToFarh时要求传入type(温标类型)和val(温度值)两个参数,实际调用时仅传入了温度值,会导致函数内部逻辑失效。
  • toLowerCase()使用错误:该方法不会修改原变量,需要将返回值赋值回原变量才会生效,且数字类型的温度值调用toLowerCase()会直接报错。
  • 温标转换公式错误:华氏度转摄氏度的正确公式是(华氏度 - 32) * 5/9,你当前的计算顺序有误,输出结果会完全不符合预期。
  • 变量未定义先使用:while循环第一次判断时farh还未声明,会抛出变量未定义的报错。

修正后的完整代码

function print(str){
    console.log(str)
}

function farhToKelvin(far){
    const cel = Math.floor((far - 32) * 5 / 9)
    const kel = cel + 273
    return kel
}

function farhToCelsius(far){
    const cel = Math.floor((far - 32) * 5 / 9)
    return cel
}

// 调整函数逻辑,实现摄氏度/开尔文转华氏度
function convertToFarh(type, val){
    type = type.toLowerCase()
    if (type == "kelvin"){
        return Math.floor((val - 273) * 9 /5 + 32)
    }
    else if(type == "celsius"){
        return Math.floor(val * 9 /5 + 32)
    }
}

var farh = ''
while (farh != "exit"){
    farh = prompt("enter a farhanhite tempature: ")
    if(farh === 'exit') break
    var type = prompt("convert it to celsius, or kelvin")
    type = type.toLowerCase()
    if (type == "celsius"){
        const c = farhToCelsius(farh)
        var val = convertToFarh('celsius', c)
        if (val < 50){
            print("it is cold, you should wear a coat")
        }
        if (val >= 50){
            print("it is hot, you should wear a tank top")
        }
    }
    else if(type == "kelvin"){
        const k = farhToKelvin(farh)
        var val = convertToFarh('kelvin', k)
        if (val < 50){
            print("it is cold, you should wear a coat")
        }
        if (val >= 50){
            print("it is hot, you should wear a tank top")
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:36:04