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

如何让const值在该if条件判断中正确执行逻辑?

问题原因与解决方法

问题出在从GitHub原始文件获取的文本大概率带有隐藏的换行符或首尾空白字符——哪怕你在GitHub上看文件内容是b-1,实际通过fetch获取到的data可能是b-1\n(末尾带换行),这就导致和你定义的current_version(纯b-1)比对永远不相等,所以每次都会触发alert。

解决步骤:

  • 对获取到的文本做首尾空白清理,用JavaScript的trim()方法,它会自动去掉字符串首尾的空格、换行、制表符等无效空白。

修改后的代码:

var current_version = "b-1"

const url = 'https://raw.githubusercontent.com/MythicalTrashcan/MY-Javascript-Bookmarklets/main/Version%20ID'
const version = await fetch(url);
const data = await version.text();

// 清理空白后再比对
if (current_version != data.trim()) {
    alert("Outdated Bookmarklet!");
}
  • 进阶优化:建议使用**严格不等运算符!==**替代!=,避免隐式类型转换带来的意外问题:
if (current_version !== data.trim()) {
    alert("Outdated Bookmarklet!");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:50:28