我正在查看Ramda cond
function 的文档并对它的行为感到困惑。文档指出 cond
...
Returns a function, fn, which encapsulates if/else-if/else logic. R.cond takes a list of [predicate, transform] pairs. All of the arguments to fn are applied to each of the predicates in turn until one returns a "truthy" value, at which point fn returns the result of applying its arguments to the corresponding transformer. If none of the predicates matches, fn returns undefined.
下面是给出的示例:
var fn = R.cond([
[R.equals(0), R.always('water freezes at 0°C')],
[R.equals(100), R.always('water boils at 100°C')],
[R.T, temp => 'nothing special happens at ' + temp + '°C']
]);
fn(0); //=> 'water freezes at 0°C'
fn(50); //=> 'nothing special happens at 50°C'
fn(100); //=> 'water boils at 100°C'
我理解该函数的[谓词,变换]
方面,但我不清楚“else”部分是如何工作的。在典型的 if/else-if/else 语句中,“else”部分不接受谓词。然而,在该示例中,每个数组都有一个谓词。也许了解 R.T
在这种情况下如何运作会有所帮助,但在文档中搜索 T
却毫无结果。
如何使用 Ramda 的 cond
函数捕获条件“else”功能以返回默认值?
最佳答案
R.T
始终返回 true
并忽略传递给它的任何参数。
这就是您传入的 100
被忽略并且仅返回 true
的原因。
R.cond
搜索每个[谓词,变换]
对,并停止搜索第一个计算结果为true
的谓词。
因此,将评估 [谓词,变换]
对中的第一个匹配实体。
如果没有任何内容为 true
,则它到达末尾并执行 R.T
谓词(始终为 true
),其作用类似于列表的其他部分。
关于javascript - Ramda `cond` else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38150870/