javascript 匹配隐式变量

javascript match implicit variable

我无法确定 javascript 中的匹配结果是否存在 隐式变量

我正在寻找的结果代码是这样的:

if(line.match(/foo{bar}/)) {
  console.log(bar_variable)
}

引用的 ^ bar_variable 应包含匹配组结果。 有这样的吗?

不,没有。 String.match() returns:

An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

所以你可以这样做:

if (bar_variable = line.match(/foo{bar}/)) {
  console.log(bar_variable)
}

为了避免使用全局符号,您可以这样做,但它确实有点丑陋:

{
  let bar_variable;
  if (bar_variable = line.match(/foo{bar}/)) {
    console.log(bar_variable);
  }
}

据我所知你做不到 if (let x = ...) 但我可能是错的。