链式操作 #
Math.js 通过将一个值包装到 Chain 对象中来支持链式操作。可以使用函数 math.chain(value) (以前是 math.select(value)) 创建一个链。Math 命名空间中所有可用的函数都可以通过链来执行。函数将以链的值作为第一个参数执行,然后是函数调用本身提供的额外参数。
math.chain(3)
.add(4)
.subtract(2)
.done() // 5
math.chain( [[1, 2], [3, 4]] )
.subset(math.index(0, 0), 8)
.multiply(3)
.done() // [[24, 6], [9, 12]]
API #
Chain 的构造如下:
math.chain()
math.chain(value)
Chain 拥有 math 命名空间中所有可用的函数,以及一些特殊函数:
done()结束链式操作并返回链的值。valueOf()与done()相同,返回链的值。toString()对链的值执行math.format(value),返回值的字符串表示形式。
请注意,“rest”或“…”参数不能跨越链中的值和函数调用。例如:
math.chain(3).median(4,5).done() // throws error
不会计算 3、4 和 5 的中位数。