用单个值初始化数组 [英] Initializing an Array with a Single Value

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

问题描述

是否有更紧凑的方式来进行这种初始化?

Is there a more compact way to do this sort of initialization?

for (var i = 0; i < arraySize; i++) array[i] = value;

推荐答案

while(arraySize--) array.push(value);

(我知道)没有初始化

更新

自4年前发布此答案以来,人们似乎一直在这里回来寻找此答案.为了进行基准测试,我使用了 JSPerf 一些不同的解决方案.

Since ever posting this answer 4 years ago, people seem to keep coming back here for this answer. For benchmarking purposes I made a JSPerf with some different solutions.

尽管很短,但上面的解决方案并不是最快的解决方案.保持相同的短样式,但具有更好的性能:

The solution above here isn't the quickest, although it's short. To stick to the same short style, but with a better performance:

while(size--) array[size] = value;


2016年2月更新使用更多测试用例的新版本对JSPerf进行了更新.


Update Feb 2016 Updated the JSPerf with a new revision with more testcases.

如果性能无关紧要,并且您需要单线:

If performance doesn't matter and you want a one-liner:

var value = 1234, // can be replaced by a fixed value
    size  = 1000, // can be replaced by a fixed value
    array = Array.apply(null,{length: size}).map(function() { return value; });

更高效的解决方案(在一个肮脏的行中):请注意:这会替换范围内现有的值,大小和i变量

A more performant solution (in one, dirty, line): Be aware: this replaces existsing value, size and i variables in the scope

for(var i = 0, value = 1234, size = 1000, array = new Array(1000); i < size; i++) array[i] = value;

这篇关于用单个值初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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