【问题标题】:Array destructuring with a ternary operator使用三元运算符进行数组解构
【发布时间】:2019-04-28 01:44:26
【问题描述】:

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

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

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

【问题讨论】:

  • 请同时添加想要的结果 - 以及一些使用案例及其结果。
  • ...[] 毫无意义。

标签: javascript arrays ecmascript-6 destructuring


【解决方案1】:

代替

[...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)])]);

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      如果我理解正确,如果 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']));

      【讨论】:

      • 郑重声明,我更喜欢@OriDrori 的解决方案;)
      猜你喜欢
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 2021-05-12
      • 2012-03-25
      • 2010-12-20
      • 2021-10-31
      • 1970-01-01
      相关资源
      最近更新 更多