Skip to content

Conversation

wumo1016
Copy link

[中文版模板 / Chinese template]

🤔 This is a ...

  • New feature
  • Bug fix
  • TypeScript definition update
  • Bundle size optimization
  • Performance optimization
  • Enhancement feature
  • Refactoring
  • Update dependency
  • Code style optimization
  • Test Case
  • Branch merge
  • Site / documentation update
  • Demo update
  • Workflow
  • Chore
  • Other (about what?)

🔗 Related issue link

💡 Background and solution

📝 Changelog

Language Changelog
🇺🇸 English
🇨🇳 Chinese

☑️ Self-Check before Merge

⚠️ Please check all items below before requesting a reviewing. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • TypeScript definition is updated/provided or not needed
  • Changelog is provided or not needed

🚀 Summary

copilot:summary

🔍 Walkthrough

copilot:walkthrough

@imsunhao
Copy link

这两段写法的目的相同——都是想得到 value 的类型名(如 "Array", "Object", "Number" 等),但实现方式和细节略有不同


🧩 第一种写法

return {}.toString
  .call(value)
  .replace(/^\[object /, '')
  .replace(/]$/, '');

✅ 原理

  • {}.toString 实际上等价于 Object.prototype.toString

  • .call(value) 调用时会返回类似 "[object Array]" 这样的字符串。

  • 之后用正则 replace 去掉前缀 "[object " 和结尾 "]",得到 "Array"

⚙️ 特点

  • 显式地用正则替换字符串

  • 不依赖固定的下标(更语义化一点)。

  • 稍微慢一点(正则匹配 + 两次替换)。


🧩 第二种写法

return Object.prototype.toString.call(value).slice(8, -1);

✅ 原理

  • 同样用 Object.prototype.toString.call(value)

  • 它返回 "[object XXX]",其中 "XXX" 的起始索引是 8("[object " 长度为 8)。

  • slice(8, -1) 截取中间部分得到 "XXX"

⚙️ 特点

  • 更简洁且性能更好(只做字符串切片,没有正则)。

  • 可读性稍弱:8-1 是“魔法数字”,需要知道格式细节。


✅ 总结对比

对比项 第一种写法 第二种写法
实现方式 正则替换 字符串截取
可读性 较语义化 较紧凑但依赖 magic number
性能 稍慢 更快
推荐 ✅ 不常用或教学场景 ✅ 实际项目中更推荐

👉 推荐写法:

Object.prototype.toString.call(value).slice(8, -1);

因为它更直接、性能更好,也被许多框架(如 Lodash、Vue 内部)采用。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants