使用N个元素创建一个没有旧的'new Array(N)'的数组的正确方法?

时间:2021-04-19 21:21:25

Whenever I work with arrays, I always use the [] style, however, when I want to create an array with a fixed amount of elements I use new Array(N) (I don't know any other way of doing this)

每当我使用数组时,我总是使用[]样式,但是,当我想创建一个具有固定数量元素的数组时,我使用new Array(N)(我不知道其他任何方式)

I thought it wasn't big deal, until I read these strong words about this:

我认为这不是什么大问题,直到我读到这些强烈的话:

Anyone doing this, using “new Array()” instead of “[]“, or “new Object()” instead of “{}” needs to relearn JavaScript.

任何人这样做,使用“new Array()”而不是“[]”,或“new Object()”而不是“{}”需要重新学习JavaScript。

I really want to avoid writting bad code. Anyone mind tell me the right direction to go?

我真的想避免写错代码。有谁介意告诉我正确的方向?

3 个解决方案

#1


5  

I wouldn't worry too much about some random comment on a blog in 2006. Especially since your use case isn't just new Array(). You're using the special-case constructor that is provided specifically for this purpose.

我不会太担心2006年博客上的随机评论。特别是因为你的用例不仅仅是新的Array()。您正在使用专门为此目的提供的特殊情况构造函数。

Besides, using new Array() instead of [] is hardly the worst thing someone can do with JS.

此外,使用新的Array()而不是[]几乎不是人们可以用JS做的最糟糕的事情。

#2


1  

function repeat(str, len){
    str= str || '';
    len= len || 1;
    return Array(len+1).join(str);
}

repeat('*',25)

// returned value: (String)

#3


0  

I know this question is pretty old, but here's how I would code it as an alternative to new Array(size), using JavaScript's literal syntax.

我知道这个问题已经很老了,但是这里我是如何使用JavaScript的文字语法将它编码为新数组(大小)的替代品。

var arr = [];
arr.length = size;

#1


5  

I wouldn't worry too much about some random comment on a blog in 2006. Especially since your use case isn't just new Array(). You're using the special-case constructor that is provided specifically for this purpose.

我不会太担心2006年博客上的随机评论。特别是因为你的用例不仅仅是新的Array()。您正在使用专门为此目的提供的特殊情况构造函数。

Besides, using new Array() instead of [] is hardly the worst thing someone can do with JS.

此外,使用新的Array()而不是[]几乎不是人们可以用JS做的最糟糕的事情。

#2


1  

function repeat(str, len){
    str= str || '';
    len= len || 1;
    return Array(len+1).join(str);
}

repeat('*',25)

// returned value: (String)

#3


0  

I know this question is pretty old, but here's how I would code it as an alternative to new Array(size), using JavaScript's literal syntax.

我知道这个问题已经很老了,但是这里我是如何使用JavaScript的文字语法将它编码为新数组(大小)的替代品。

var arr = [];
arr.length = size;