使用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
相关产品推荐
相关产品推荐

