有没有办法在不指定 if 和 else 的情况下处理展开运算符中的 null?
在下面的场景中,我只想在 assignedStudents
不是未定义的情况下传播它。
如果我不使用 if else 就这样做,我会得到错误:
TypeError: Invalid attempt to spread non-iterable instance
为了处理这个问题,我使用了 if else,但认为有更好/优雅的方法来做到这一点。
let questions;
if (assignedStudents) {
questions = [
...assignedStudents,
{
questionId: randomId,
question: ''
}
];
} else {
questions = [
{
questionId: randomId,
question: ''
}
];
}
最佳答案
你的意思是使用 nullish coalescing operator 这样的东西吗?
const questions = [
...(assignedStudents ?? []),
{
questionId: randomId,
question: ""
}
]
当然,如果 assignedStudents
是不可迭代的(例如 Number
或 Object
),这将无法保护您。它不是那么花哨,但如果您只想对数组进行操作,请使用 Array.isArray()
const questions = [
...(Array.isArray(assignedStudents) ? assignedStudents : []),
{
questionId: randomId,
question: ""
}
]
因为你用 typescript 标记了这个问题,您应该将 assignedStudents
标记为可为 null 的数组,例如
assignedStudents?: Something[]
在这种情况下,上述情况不再是问题。
关于javascript - 当值为 null 时使用扩展运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64328689/