Array.map似乎并没有对未初始化数组工作 [英] Array.map doesn't seem to work on uninitialized arrays

查看:133
本文介绍了Array.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?

考虑这个code段我在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.

推荐答案

如果您想填补一个数组,你可以做到这一点。

If you'd like to fill an array, you can do this

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

在的一些读取一个<一个href=\"http://stackoverflow.com/questions/18947892/creating-range-in-javascript-strange-syntax/18949651#18949651\">posts在评论联系,我发现这也可以写成

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 未定义值将无法正常工作。


However, trying to use .map on undefined values will not work.

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

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

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

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

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