Array.map 似乎不适用于未初始化的数组 [英] Array.map doesn't seem to work on uninitialized arrays

查看:38
本文介绍了Array.map 似乎不适用于未初始化的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 map 函数在未初始化的数组上设置默认值,但似乎不起作用,关于如何设置默认值的任何想法?

I'm trying to set default values on an uninitialized array using the map function but it doesn't seem to work, any ideas on how to set default values?

考虑一下我在 Chrome 控制台中尝试过的这段代码.

Consider this code snippet I tried in Chrome console.

> var N = 10;
> var x = new Array(N);
> x
  [undefined x 10]

> x.map(function(i) { return 0;});
  [undefined x 10]

我期望数组被初始化为 0.

I was expecting the array to be initialized to 0's.

推荐答案

如果你想填充一个数组,你可以使用 Array(5).fill() 然后方法会按预期工作 - 请参阅 aasha7 的替代相关答案.较旧的预填充方法包括:

If you'd like to fill an array, you can use Array(5).fill() and the methods will then work as expected--see the alternate related answer from aasha7. Older pre-fill approaches include:

Array.apply(null, new Array(5)).map(function() { return 0; });
// [ 0, 0, 0, 0, 0 ]

阅读一些评论中链接的帖子后,我发现这也可以写成

After some reading one of the posts linked in the comments, I found this can also be written as

Array.apply(null, {length: 5}).map(function() { return 0; });

<小时>

但是,尝试对未定义的值使用 .map 是行不通的.

x = new Array(10);
x.map(function() { console.log("hello"); });

// so sad, no "hello"
// [ , , , , , , , , ,  ]

.map 将跳过未定义的值 :(

.map will skip over undefined values :(

这篇关于Array.map 似乎不适用于未初始化的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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