迭代超范围的功能方式(ES6 / 7) [英] functional way to iterate over range (ES6/7)

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

问题描述

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

我尝试过,

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

但翻译成

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

这不是我预期的。



编辑:



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

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

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

解决方案

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

$ b $ map((_,i)=> i * i); b

  Array(8).fill() 


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++) {
   return i * i;
}
return cols;

I tried like,

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

but that translated to

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

which is not what I expected.

EDIT:

@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.

解决方案

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

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

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

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