VSCode 片段:将可变数量的对象添加到类构造函数 [英] VSCode snippet: add variable number of objects to a class constructor
问题描述
我正在尝试创建一个允许我创建 JS 构造函数的简单代码段.到目前为止,我所拥有的是
I am trying to create a simple snippet that allows me to create JS Constructors. So far, what I have is
"class constructor": {
"prefix": "class",
"body": [
"class ${1:ClassName} {",
"\t\tconstructor({${2:thisName}: ${2}}) {",
"\t\t\tthis.${2} = ${2}",
"\t}",
"}"
],
"description": "class constructor template"
},
这按预期工作,但我想看看是否可以添加多个条目,这也为 this
创建一个新行,但在这种情况下,代码段运行一次我填写了 $2{thisName}
的详细信息.我希望的是能够添加多个键值对.
This works as expected, but what I am trying to see if it is possible to add multiple entries which also creates a new line for this
, but in this case, the snippet runs its course once I fill in the details for $2{thisName}
. What I am hoping for is the ability to add multiple key value pairs.
所以而不是结束于:
class ClassName {
constructor({ thisName: thisName}) {
this. thisName = thisName
}
}
我希望能够添加其他项目,使其看起来像;其中 this.another = another
的新行是自动创建的.
I would like to be able to add other items so that it looks like; where a new line for this.another = another
is created automatically.
class ClassName {
constructor({ thisName: thisName, another: another}) {
this. thisName = thisName
this.another = another // this is create
}
}
${3}..
在这里不起作用,因为可能有任意数量的项目.
The ${3}..
doesn't work here because there could be any amount of items.
推荐答案
试试这个:
"class constructor": {
"prefix": "class",
"body": [
"class ${1:ClassName} {",
"\t\tconstructor({${2/([^,]+)([,\\s]*|)/$1: $1${2:+, }/g}}) {",
"${2/([^,]+)([,\\s]*|)/\t\t\tthis.$1 = $1${2:+\n}/g}",
"\t}",
"}"
],
"description": "class constructor template"
},
在制作一个可以使用可变数量参数的 vscode 片段 以获得更多解释.
您可以在一个片段中使用任意数量的参数,只要您在同一个正则表达式捕获组中捕获它们 - 这里每个参数都在捕获组 $1 中.
You can use any number of arguments in a snippet as long as you capture them in the same regex capture group - here each arg is in capture group $1.
然后每个都被替换了!在你的情况下 \t\t\tthis.$1 = $1${2:+\n
第二次.在tabs之后,捕获组用于this.$1 = $1
Then each one is replaced! In your case by \t\t\tthis.$1 = $1${2:+\n
the second time. After the tabs, the capture group is used in this.$1 = $1
然后检查捕获组 2 ${2:+\n}
.它要么有 、
,要么什么都没有.如果有东西,加一个\n
,否则什么都不加.
Then capture group 2 is inspected ${2:+\n}
. It either has the ,
or nothing. If it has something, add a \n
, otherwise nothing will be added.
为了让这个正则表达式工作,你应该输入你的参数
For this regex to work you should enter your args as
arg1、arg2、arg3、arg4
-- 带逗号分隔符(逗号后有或没有空格).在您的最后一个参数点击 tab
以触发代码段转换之后.
-- with comma separators (withor without spaces after the commas). After your last argument hit tab
to fire the snippet transform.
这篇关于VSCode 片段:将可变数量的对象添加到类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!