简体   繁体   中英

Array destructuring with a ternary operator

I am trying to concat (with uniques values) two arrays and if the second array sometimes is a string.

Maybe it have a bug, but these are my three tryings:

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)]

Instead of

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

take, watch the round, square, round and squere closing brackets at the end.

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

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

Instead of using spread, you can use Array.concat() , because it treats combine arrays and values in the same way:

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

If I understand correctly, if the a parameter is a string, and not a collection, searching unique values and the need for a Set is moot. Then you could short circuit as typeof a === 'string' ? [a] : [...new Set(a)] 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'])); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM