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

使用typeof运算符获取对象值类型却得到string而非array的问题

问题原因

你用for...in循环遍历对象时,变量p拿到的是对象的属性名(键),而对象的属性名本质都是字符串类型,所以typeof(p)返回string是正常的——你判断的是属性名的类型,不是属性值(数组)的类型。

修正代码

要获取属性值的类型,需要通过required[p]访问对应的属性值,再做类型判断:

const add = "add"
const edit = "edit"
const required = {
  user: [add, edit],
  profile: [edit],
}

for (let p in required) {
  // 访问属性值并判断类型
  console.log(p, typeof(required[p]), Array.isArray(required[p]))
}

输出结果:

user object true
profile object true

补充说明:typeof判断数组时会返回object,这是JS的历史遗留特性,如果要准确判断是否为数组,推荐使用Array.isArray()方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:44:51