TS不能用两字符相减得到ascii码差值

Zesari 发布于 2025-01-20 97 次阅读


背景

在做 763. 划分字母区间 - 力扣(LeetCode)时,需要遍历整个字符串,以记录每个字符串的最远出现位置

之前好像写Python写习惯了,直接用两个字符相减了

hashTable[s[i] - 'a'] = i

报错

error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

算术运算符左侧值必须是 anynumber bigint 或枚举类型

修正:用 `charCodeAt` 方法获取ASCII值

let charIndex = s.charCodeAt(i) - 'a'.charCodeAt(0)
hashTable[charIndex.toString()] = i

虽然字符相减得不到ASCII值的差,但是两个字符可以比较大小

console.log('2' > '1') // true
console.log('b' > 'a') // true

Hello, It's me.
最后更新于 2025-01-21