给定两个函数(预期输出为 //d
):
function fearNotLetter(str) {
for (let i = 0; i < str.length; i++) {
let code = str.charCodeAt(i)
if (code !== str.charCodeAt(0) + i) {
return String.fromCharCode(str.charCodeAt(0) + i)
}
}
return undefined
}
fearNotLetter("abce");
// d
还有
function fearNotLetter(str) {
for (let i in str) {
let code = str.charCodeAt(i)
if (code !== str.charCodeAt(0) + i) {
return String.fromCharCode(str.charCodeAt(0) + i)
}
}
return undefined
}
fearNotLetter("abce");
// ϊ
我发现使用 for...in
循环将 i
的值强制转换为字符串。根据我的理解,if语句失败,因为i
的值不再是数字,因此无法进行求和。
我的问题是,为什么 JS 不将 i
强制返回 if 语句 (str.charCodeAt(0) + i )
中的数字?并允许以与 for...loop
相同的方式完成求和?
是因为一旦i
在函数内被强制,就不能再次被强制吗?
最佳答案
在第一个函数中,当您将i
初始化为数字时,将其类型设置为number
。在第二个函数中,i
是可迭代的键,因此这意味着它的类型是string
。根本没有进行类型转换。
关于javascript - 为什么 JS 不将 i 的值强制为 "for in loop"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59457409/