使用三元运算符进行数组解构

Array destructuring with a ternary operator

我正在尝试连接(具有唯一值)两个数组,如果第二个数组有时是一个字符串。

也许它有一个错误,但这是我的三个尝试:

let a = 'abcdefg'
// First try
[...new Set([...[], ...(typeof(a) == 'string'? [a]: a))]
// Second try
[...new Set([...[], [(typeof(a) == 'string'? ...[a]: ...a)]]
// Third try
[...new Set([...[], (typeof(a) == 'string'? ...[a]: ...a)]

而不是

[...new Set([...[], ...(typeof a === 'string' ? [a] : a))]

看一下最后的圆括号、方括号、圆括号和方括号。

[...new Set([...[], ...(typeof a === 'string' ? [a] : a)])]
//                                                      ^

let a = 'abcdefg'

console.log([...new Set([...[], ...(typeof a === 'string' ? [a] : a)])]);

您可以使用 Array.concat() 而不是传播,因为它以相同的方式处理组合数组和值:

const a = 'abcdefg'
console.log([...new Set([].concat([], a))])
console.log([...new Set([].concat([], [a]))])

如果我理解正确,如果 a 参数是一个字符串,而不是一个集合,则搜索唯一值和对 Set 的需求是没有意义的。然后你可以短路 typeof a === 'string' ? [a] : [...new Set(a)]

let a = 'abcdefg'

const createArr = a => typeof a === 'string' ? [a] : [...new Set(a)];

console.log(createArr(a));
console.log(createArr([a,a,'aa']));