【问题标题】:Ts destructuring array of string to be a parametersTs解构字符串数组作为参数
【发布时间】:2021-11-19 09:02:51
【问题描述】:

您好,我有一组键

Ex1:

const arrWithKeys = ['a','b','c']

我想把它们作为参数,因为我不想写多次,有办法实现吗?。

Ex2:

const [...arrWithKeys] = someFunc(arrWithKeys)

然后我可以将它用作参数

const title = a.title
  • Ex2 不起作用

【问题讨论】:

  • 您想使用someFunc 来检索与给定键集对应的值吗?

标签: typescript ecmascript-2016


【解决方案1】:

您可以在遍历数组时使用括号参数语法,例如

const result: {[key: string]: any} = someFunc(arrWithKeys)
for (key of arrWithKeys) { // or (key in result)
  doSomethingWith(result[key])
}

根据数组的内容声明一组局部变量可能不是一个好主意。最好将someFunc 的结果保存在某个对象中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    相关资源
    最近更新 更多