如何在JavaScript中模拟let表达式? [英] How to simulate let expressions in JavaScript?

查看:74
本文介绍了如何在JavaScript中模拟let表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 :

const take = (n, [x, ...xs]) =>
    n === 0 || x === undefined ?
    [] : [x, ...take(n - 1, xs)];

console.log(take(7, [1, 2, 3, 4, 5])); // [1, 2, 3, 4, 5]
console.log(take(3, [1, 2, 3, 4, 5])); // [1, 2, 3]
console.log(take(1, [undefined, 1]));  // []

不适用于带有undefined的数组,因为x === undefined并不是测试数组是否为空的最佳方法.以下代码可解决此问题:

As you can see, it doesn't work for arrays with undefined because x === undefined is not the best way to test whether an array is empty. The following code fixes this problem:

const take = (n, xs) =>
    n === 0 || xs.length === 0 ?
    [] : [xs[0], ...take(n - 1, xs.slice(1))];

console.log(take(7, [1, 2, 3, 4, 5])); // [1, 2, 3, 4, 5]
console.log(take(3, [1, 2, 3, 4, 5])); // [1, 2, 3]
console.log(take(1, [undefined, 1]));  // [undefined]

但是,编写xs[0]xs.slice(1)并不那么优雅.另外,如果您需要多次使用它们,这是有问题的.您要么必须复制代码并进行不必要的额外工作,要么必须创建一个块作用域,定义常量并使用return关键字.

However, writing xs[0] and xs.slice(1) isn't as elegant. In addition, it's problematic if you need to use them multiple times. Either you'll have to duplicate code and do unnecessary extra work, or you'll have to create a block scope, define constants and use the return keyword.

最好的解决方案是使用 let表达式.不幸的是,JavaScript没有它们.那么,如何在JavaScript中模拟let表达式?

The best solution would be to use a let expression. Unfortunately, JavaScript doesn't have them. So, how to simulate let expressions in JavaScript?

推荐答案

在Lisp中,一个 let表达式只是左左lambda的语法糖(即立即调用的函数表达式).例如,考虑:

In Lisp, a let expression is just syntactic sugar for a left-left lambda (i.e. an immediately-invoked function expression). For example, consider:

(let ([x 1]
      [y 2])
  (+ x y))

; This is syntactic sugar for:

((lambda (x y)
    (+ x y))
  1 2)

在ES6中,我们可以使用箭头函数默认参数来创建IIFE看起来像一个let表达式,如下所示:

In ES6, we can use arrow functions and default parameters to create an IIFE that looks like a let expression as follows:

const z = ((x = 1, y = 2) => x + y)();

console.log(z);

使用此hack,我们可以如下定义take:

Using this hack, we can define take as follows:

const take = (n, xxs) =>
    n === 0 || xxs.length === 0 ?
    [] : (([x, ...xs] = xxs) => [x, ...take(n - 1, xs)])();

console.log(take(7, [1, 2, 3, 4, 5])); // [1, 2, 3, 4, 5]
console.log(take(3, [1, 2, 3, 4, 5])); // [1, 2, 3]
console.log(take(1, [undefined, 1]));  // [undefined]

希望有帮助.

这篇关于如何在JavaScript中模拟let表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆