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

如何在JavaScript中仅比较两个字符串的首字符?附异常代码求助

修复你的字符串首字符比较函数

嘿,我发现你的函数问题出在哪啦!你用了wordOne.substring(0)和wordTwo.substring(0),但substring方法如果只传一个参数(比如0),它会返回从该索引开始到字符串末尾的全部内容——所以你的函数其实是在比较两个完整字符串是否相等,而不是首字符!

几种正确的实现方式:

方法1:用substring(0, 1)指定截取长度

substring(startIndex, endIndex)的第二个参数是结束索引(不包含),传0,1就能精准截取第一个字符:

function compare(wordOne, wordTwo) {
  return wordOne.substring(0, 1) === wordTwo.substring(0, 1);
}
console.log(compare("house", "hell")); // 输出 true,因为首字符都是'h'

方法2:用charAt(0)直接获取首字符

charAt(index)方法专门用来获取指定索引的字符,语义更清晰:

function compare(wordOne, wordTwo) {
  return wordOne.charAt(0) === wordTwo.charAt(0);
}
console.log(compare("house", "hell")); // 输出 true

方法3:用方括号[0]访问字符(ES5+支持)

这是最简洁的写法,直接通过索引访问字符串的字符:

function compare(wordOne, wordTwo) {
  return wordOne[0] === wordTwo[0];
}
console.log(compare("house", "hell")); // 输出 true

另外提个小优化:你的函数里的if-else可以直接简化成返回比较结果,因为比较本身就会返回布尔值,不用多此一举写return true/false哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:03:11