在haskell中可以使用as模式来实现对原参数的声明
例如 :
-- haskell
test :: String -> String
test all@(x:xs) = "arg is :" ++ all ++ " head is :" ++ [x] ++ " tail is :" ++ xs
-- test "123" : "arg is :123 head is :1 tail is :23"
但在js中我并没有找到相关的内容可以获取到这个'all'。只能通过这种方法来同时声明原参数以及'head'和'tail'
// 每次使用这个all都要重新创建一个数组进行计算一次,性能略差。
const test1 = ([head, ...tail]) => `arg is : ${[head, ...tail]} head is : ${head} tail is : ${tail}`
// 需要多写一个声明语句,并且无法在一行内完成函数体,不整洁
const test2 = (all) => {
let [head, ...tail] = all
return `arg is : ${all} head is : ${head} tail is : ${tail}`
}
// 各种意义上来说都不太行
function test3([head, ...tail]) {
return `arg is : ${arguments[0]} head is : ${head} tail is : ${tail}`
}
目前我只能想到这几种方法去模拟这个as模式。请问各位js有没有什么类似与可选链那种实验性的方法可以实现haskell中的as模式。咱们前端都是十分时髦并且喜欢追求新事物的,所以说一定有的吧,这个!!!
这是你要的吗?