使用带有 array.entries 的可选链接
Using optional chaining with array.entries
只是想了解可选链接,不确定它是否可以在以下情况下与 .entries
一起使用,即:
for (const [index, val] of Array.from(myArray)?.entries()) {
if (val.status === 1) {
. . .
. . .
}
}
如果myArray
是空的,我基本上不想继续。
如果您寻找一个简短的空值检查,我认为您的问题不是来自 Array.from
,而是来自 myArray
变量。如果 myArray
未定义,Array.from(myArray)?.entries()
将抛出错误
const myArray = undefined
const entries = Array.from(myArray)?.entries() //throw an error
如果你想克服这个问题,你需要使用 short circuit evaluation 在 myArray
未定义或 null
时分配默认值 []
const myArray = undefined
const entries = Array.from(myArray || []).entries() //working!
如果 myArray
已经是一个数组(或者可能是一个未定义的值),你也可以去掉 Array.from
const myArray = undefined
const entries = myArray?.entries() || [] //assign a default value for your loop
只是想了解可选链接,不确定它是否可以在以下情况下与 .entries
一起使用,即:
for (const [index, val] of Array.from(myArray)?.entries()) {
if (val.status === 1) {
. . .
. . .
}
}
如果myArray
是空的,我基本上不想继续。
如果您寻找一个简短的空值检查,我认为您的问题不是来自 Array.from
,而是来自 myArray
变量。如果 myArray
未定义,Array.from(myArray)?.entries()
将抛出错误
const myArray = undefined
const entries = Array.from(myArray)?.entries() //throw an error
如果你想克服这个问题,你需要使用 short circuit evaluation 在 myArray
未定义或 null
[]
const myArray = undefined
const entries = Array.from(myArray || []).entries() //working!
如果 myArray
已经是一个数组(或者可能是一个未定义的值),你也可以去掉 Array.from
const myArray = undefined
const entries = myArray?.entries() || [] //assign a default value for your loop