Javascript 到 return "false" 如果没有正则表达式匹配

Javascript to return "false" if no regex matches

以下代码 ,并且——据我所知——将所有匹配项放入一个数组中。

// stores an array of any length (0 or more) with the matches
var matches = inputData.body.match(/\b[\w-]{32}\b/g)

// the .map function executes the nameless inner function once for each element of the array and returns a new array with the results
return matches.map(function (m) { return {str: m} })

我现在需要 return something 的代码,以防没有匹配的表达式,例如。字符串 "false".

我无法让这个添加工作...

// stores an array of any length (0 or more) with the matches
var matches = inputData.body.match(/\b[\w-]{32}\b/g)

if (matches == null){
    return 'false'
}

// the .map function executes the nameless inner function once for each element of the array and returns a new array with the results
return matches.map(function (m) { return {str: m} })

我应该如何有条件地return在空的情况下做一些事情?

调用者需要一个对象数组或单个对象(大概被视为一个对象的数组)。所以 return 一个对象。

if (matches == null) {
    return { str: "false"; }
}
return matches.map(function (m) { return {str: m} });

或在单个语句中:

return matches == null ? { str: "false"; } : matches.map(function (m) { return {str: m} });

调用者可能需要一个数组,如果没有匹配项,它应该是一个空数组。您不需要 if 语句,只需执行以下操作:

return (matches || []).map(function (m) { return {str: m} })

要测试正则表达式是否匹配特定模式,您应该使用 test() 方法,其中 returns true/false.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test