2017-10-06 260 views
0

以下代码examines the content of inputData.body for a 32-character string match,并且 - 尽我所知,将任何匹配放在数组中。如果没有正则表达式匹配,则返回“false”

// 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} }) 

我现在需要的代码中没有匹配的表达式的情况下,例如返回东西。字符串"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} }) 

我应该如何去空虚的情况下,有条件地返回的东西吗?

+0

被包裹在函数的代码? –

+2

我认为你的代码应该可以工作。 – Barmar

+0

你确定调用者已经准备好获得一个字符串作为该函数的结果吗?它可能期望一个数组。 – Barmar

回答

0

调用者需要一个对象数组或单个对象(可能被视为一个对象的数组)。所以返回一个单一的对象。

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} }); 
+0

注意以上所有。需要一些肯定的输出,而不是填充一个空的任何东西,在上面用'false'填充'str'的​​地方似乎是这样做的,并且使我能够在后续步骤中测试“false”这个词。不漂亮,但我需要的。我想我需要这个条件,虽然..? 'if(matches == null){ return {str:'false'}; } else { return matches.map(function(m){return {str:m}}) }'? –

+0

如果'if'执行'return',则不需要'else'。 – Barmar

+1

我查看了文档,它似乎说空数组是可以的。 **如果Zapier的Code是Zap的触发器,并且返回一个空数组,则不会发生任何事情** – Barmar

0

调用者可能希望一个数组,这应该是如果没有匹配的空单。你不需要if声明,只是这样做:

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