我有一个函数可以删除集合中的标记,有时参数可以是数组,有时只是变量。
我这样做解析,只是想知道是否有更干净的方法?
我已经尝试过[…标签],但这只是拆分了string
this.removeNotificationTag = async (userId, tag) => {
const tagsToRemove = Array.isArray(tag) ? tag : [tag];
// if tag is a variable make it an array.
};
尝试了排列运算符,但这只是拆分了字符串。
您的代码很好,这是通用的方法。
如果您的输入是string
或string[]
,您也可以使用typeof
:
this.removeNotificationTag = async (userId, tag) => {
const tagsToRemove = typeof tag === 'string' ? [tag] : tag;
// the rest of the code...
};
但这是不太通用的,代码长度相同,所以我会坚持你最初写的内容。