Javascript中是否有等效的构造。如果没有,你将如何创建一个?
下面是对中缀运算符在 Haskell 中的作用的简单解释:
JavaScript 没有列表类型,但它有Array
s。
您可以使用...
var newArr = [val].concat(arr);
或者,您可以使用unshift()
添加到数组的前面,但它会改变原始数组。
JavaScript 没有:
运算符、运算符重载或看起来像运算符的方法,因此您无法获得与 Haskell 类似的语法。
我看到 Leila Hamon 已经链接到这篇关于在 JS 中模拟中缀运算符的文章。
但我认为一个例子可能对其他人有用。
以下是如何破解Number
和Boolean
原型来处理链式中缀表达式,例如4 < 5 < 10
.
您可以通过将更多方法应用于更多原型来进一步扩展它。它有点难看,但对于使查询不那么冗长可能很有用。
//Usage code
(4) .gt (6) .gt (4) //false
(100) .lt (200) .lt (400) . gt(0) . gt(-1)//true
(100) [ '>' ] (50) [ '<' ] (20)//false
//Setup Code
(function(){
var lastVal = null;
var nP = Number.prototype
var bP = Boolean.prototype
nP.gt = function(other){
lastVal = other;
return this > other;
}
nP.lt = function(other){
lastVal = other;
return this < other;
}
bP.gt = function(other){
var result = lastVal > other;
lastVal = other;
return result;
}
bP.lt = function(other){
var result = lastVal < other;
lastVal = other;
return result;
}
bP['<'] = bP.lt
bP['>'] = bP.gt
nP['<'] = nP.lt
nP['>'] = nP.gt
})()
它不是最漂亮的,但它可能有助于在您想要中缀的地方提高可读性,以便您的代码读起来像散文
function nfx(firstArg, fn, secondArg){
return fn(firstArg, secondArg);
}
// Usage
function plus(firstArg, secondArg) {
return firstArg + secondArg;
}
nfx(1, plus, 2);