将 Array.map 与新的 Array 构造函数一起使用 [英] Using Array.map with new Array constructor

查看:33
本文介绍了将 Array.map 与新的 Array 构造函数一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将 new Array() 构造函数与 map 一起使用,以便创建一个用于创建元素列表的单行代码.像这样:

I was trying to use new Array() constructor with map in order to create a one-line code that creates a list of elements. Something like this :

let arr = new Array(12).map( (el, i) => {
  console.log('This is never called');
  return i + 1;
});

阅读文档,行为是有道理的.

Reading docs, the behaviour makes sense.

基本上文档说即使对于数组中声明的未定义值也会执行 map 的回调,但例如在创建空数组时不会像之前的代码那样.

Basically docs say that callback of map will be executed even for declared undefined values in array, but not for example when creating empty Arrays like the code before.

所以这应该有效:

var arr = new Array(12);

for(let i = 0; i < arr.length ; i++){
  arr[i] = undefined;
}

let list = arr.map( (e, i) => {
  console.log(i + 1);
  return i + 1;
});

所以,我们也可以这样做:

So, We also can do something like this :

let newArray = (length) => {
  let myArray = new Array(length);
  for(let i = 0; i < length; i++) myArray[i] = undefined;
  return myArray;
};

console.log( newArray(12).map( (el, i) => i + 1 ) );

所以我的问题.有没有更好/漂亮的方法来使用地图功能?

提前致谢!

推荐答案

您可以使用 Array#from 创建一个已传递长度的数组.

You can use Array#from to create an array having passed length.

Array.from({length: 12}, (e, i) => i + 1);

这篇关于将 Array.map 与新的 Array 构造函数一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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