javascript - 为什么 JS 不将 i 的值强制为 "for in loop"?

标签 javascript coercion

给定两个函数(预期输出为 //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/

相关文章:

javascript - 更改小数点

javascript - 如何从日期中检索星期几

javascript - Electron:惰性元素类型必须解析为类或函数(在生产模式下)

types - 双重强制什么时候有用?

actionscript-3 - AS3 : Type Coercion failed: cannot convert flash. 事件到 flash.events.MouseEvent

javascript - 重置对象键值

Javascript根据选择隐藏输入字段更改文本而不是值

javascript - 为什么 JavaScript 在连接时优先转换为字符串,而在比较时优先转换为数字?

python - 为什么 Pandas 将我的 numpy float32 强制转换为 float64?

javascript - 按类型排除 React Router 中路径参数的值