遍历范围的函数式方法 (ES6/7) [英] functional way to iterate over range (ES6/7)

查看:20
本文介绍了遍历范围的函数式方法 (ES6/7)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以更实用的方式执行以下操作的最佳方法是什么(使用 ES6/ES7)

What is the best way to do the below in more functional way (with ES6/ES7)

let cols = [];
for (let i =0; i <= 7; i++) {
   cols.push(i * i);
}
return cols;

我试过了,

return [ ...7 ].map(i => {
  return i * i;
});

但是翻译成

[].concat(7).map(function (n) {
  return n * n;
});

这不是我所期望的.

@pavlo.确实,这是一个错误.我使用的是 JSX,例如,我想要 7 个 div,(未经测试)

@pavlo. Indeed, that was a mistake. I was using JSX, and for example, I want 7 divs, (untested)

let cols = [];
    for (let i =0; i <= 7; i++) {
       cols.push(<div id={i}> ...  </div>)
    }
    return cols;

所以这个想法确实是为了减少临时变量的数量和程序感觉.

so the idea was indeed to reduce the number of temp variables and procedural feel.

推荐答案

可以创建一个空数组,填充它(否则 map 会跳过它),然后将索引映射到值:

One can create an empty array, fill it (otherwise map will skip it) and then map indexes to values:

Array(8).fill(0).map((_, i) => i * i);

这篇关于遍历范围的函数式方法 (ES6/7)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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