N8N中文教程
代码开发/Cookbook/Expressions

检查传入数据#

有时,你可能需要检查传入的数据。如果传入的数据不满足某个条件,你可能希望返回一个不同的值。例如,你想检查前一个节点中的变量是否为空,并在为空时返回一个字符串。可以使用以下代码片段:当变量为空时返回 not found

1

| ``` {{$json["variable_name"] ? $json["variable_name"] : "not found"}}


---|---
上述表达式使用了三元运算符(ternary operator)。你可以[点击此处](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)了解更多关于三元运算符的信息。

作为替代方案,你也可以使用 [空值合并运算符 (??)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing) 或 [逻辑或运算符 (||)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR):

1 2

| ```
{{$x ?? "default value"}}
{{$x || "default value"}}

---|--- 在这两种情况下,只要 $x 被设置为非空且非 false 的值,就会使用其值;否则将使用 "default value" 作为备用值。