我有一个对象,其中两个参数将数组作为它们的值。当我尝试在循环中使用
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
for...in
循环迭代对象时,您正在查询其键。const obj = { a: "first", b: "second", c: "third" }
for (let p in obj) {
console.log(p) // results: a, b, c (keys)
// can get values with key
console.log(obj[p]) // results: "first", "second", "third" (values)
}
for...in
再次为我们提供了密钥。const arr = Object.values({ a: "first", b: "second", c: "third" }) // result: ["first", "second", "third"]
for (let p in arr) {
console.log(p) // results: 0, 1, 2 (indexes)
// can get values with key
console.log(arr[p]) // results: "first", "second", "third" (values)
}
for...in
和for...of
之间的区别了。使用 for...of
为我们提供了数组的值。然而,对象的原始键在这里丢失了。问题是我们是否需要它们。const arr = Object.values({ a: "first", b: "second", c: "third" }) // result: ["first", "second", "third"]
for (let p of arr) {
console.log(p) // results: "first", "second", "third" (values)
}
for...of
,获取钥匙本来就很困难。但是,如果您使用 Object.entries()
而不是 Object.values()
将其转换为数组,则新数组将包含键及其值,然后您可以在 for...of
循环中检索它们。const arr = Object.entries({ a: "first", b: "second", c: "third" }) // result: [[a, "first"], [b, "second"], [c, "third"]]
for (let p of arr) {
console.log(p[0]) // results: a, b, c (keys)
console.log(p[1]) // results: "first", "second", "third" (values)
}
// or can use destructuring assignment instead of p
for (let [key, value] of arr) {
console.log(key) // results: a, b, c (keys)
console.log(value) // results: "first", "second", "third" (values)
}
const add = "add"
const edit = "edit"
const required = {
user: [add, edit],
profile: [edit],
}
// 1. object with "in"
for (let p in required) {
console.log(p, typeof(p))
console.log(required[p], typeof(required[p]))
}
// 2. array with "in" (Object.values)
const arr = Object.values(required)
for (let p in arr) {
console.log(p, typeof(p))
console.log(arr[p], typeof(arr[p]))
}
// 3. array with "of" (Object.values)
for (let p of arr) {
console.log(p, typeof(p))
}
// 4. array with "of" (Object.entries)
const arr_with_keys = Object.entries(required)
for (let p of arr_with_keys) {
console.log(p, typeof(p)) // ["user", ["add", "edit"]]
console.log(p[0], typeof(p[0])) // "user"
console.log(p[1], typeof(p[1])) // ["add", "edit"]
}
// or can declare key and value (destructuring assignment)
for (let [key, value] of arr_with_keys) {
console.log(key, typeof(key))
console.log(value, typeof(value))
}
Object.keys()
- MDN 文档Object.values()
- MDN 文档Object.entries()
- MDN 文档for...in
循环 - MDN 文档for...of
循环 - MDN 文档const [a, b] = ["first", "second"]
- MDN 文档这就是访问数组(值)的方式-
Object[key]
,在您的情况下翻译为required[p]
。
(
typeof
函数将arrays
记录为'object'
)
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]))
}