最有效的方法来创建填充JavaScript数组一个零? [英] Most efficient way to create a zero filled JavaScript array?

查看:141
本文介绍了最有效的方法来创建填充JavaScript数组一个零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是JavaScript创建任意长度为零充满阵列的最有效方法是什么?

What is the most efficient way to create an arbitrary length zero filled array in JavaScript?

推荐答案

虽然这是一个古老的线程,我想我的2美分添加到它。不知道如何快/慢,这是,但它是一个快速班轮。这是我做的:

Although this is an old thread, I wanted to add my 2 cents to it. Not sure how slow/fast this is, but it's a quick one liner. Here is what I do:

如果我想$与数p $ P-填写:

If I want to pre-fill with a number:

Array.apply(null, Array(5)).map(Number.prototype.valueOf,0);
// [0, 0, 0, 0, 0]

如果我想$有串P $ P-填写:

If I want to pre-fill with a string:

Array.apply(null, Array(3)).map(String.prototype.valueOf,"hi")
// ["hi", "hi", "hi"]


其他答案建议:


Other answers have suggested:

new Array(5+1).join('0').split('')
// ["0", "0", "0", "0", "0"]

但如果你想0(数量),而不是(在字符串中零)0,你可以这样做:

but if you want 0 (the number) and not "0" (zero inside a string), you can do:

new Array(5+1).join('0').split('').map(parseFloat)
// [0, 0, 0, 0, 0]

这篇关于最有效的方法来创建填充JavaScript数组一个零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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