使用 typeof() 获取对象值类型 - 接收字符串而不是数组

问题描述 投票:0回答:1

我有一个对象,其中两个参数将数组作为它们的值。当我尝试在循环中使用

typeof()
函数输出这些值的类型时,由于某种原因,我总是得到
string
类型,而不是实际的
array
值。

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

for (let p in required) {
  console.log(p, typeof(p))
}

Output:

string
string
javascript
1个回答
0
投票

这就是访问数组(值)的方式-

Object[key]
,在您的情况下翻译为
required[p]

typeof
函数将
arrays
记录为
'objects'

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

for (let p in required) {
  console.log(required[p])
}

for (let p in required) {
  console.log(typeof(required[p]))
}

© www.soinside.com 2019 - 2024. All rights reserved.