“Array()”和“Array()”有什么区别? 和“[]” 声明 JavaScript 数组时?

发布于 2024-07-23 21:00:03 字数 132 浏览 8 评论 0原文

像这样声明数组之间的真正区别是什么:

var myArray = new Array();

var myArray = [];

What's the real difference between declaring an array like this:

var myArray = new Array();

and

var myArray = [];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

谜兔 2024-07-30 21:00:04

使用隐式数组和数组构造函数创建数组之间的区别很微妙,但很重要。

当您使用创建数组时,

var a = [];

您告诉解释器创建一个新的运行时数组。 根本不需要额外的处理。 完毕。

如果你使用:

var a = new Array();

你告诉解释器,我想调用构造函数“Array”并生成一个对象。 然后,它会查找执行上下文以找到要调用的构造函数,并调用它,创建数组。

您可能会想“好吧,这根本不重要。它们是一样的!”。 不幸的是你不能保证这一点。

采取以下示例:

function Array() {
    this.is = 'SPARTA';
}

var a = new Array();
var b = [];

alert(a.is);  // => 'SPARTA'
alert(b.is);  // => undefined
a.push('Woa'); // => TypeError: a.push is not a function
b.push('Woa'); // => 1 (OK)

在上面的示例中,第一个呼叫将如您所期望的那样提醒“SPARTA”。 第二个不会。 你最终会看到未定义的。 您还会注意到,b 包含所有本机 Array 对象函数,例如 push,而另一个则不包含。

虽然您可能期望这种情况发生,但它只是说明了 []new Array() 不同的事实。

如果您知道只需要一个数组,最好只使用 [] 。 我也不建议四处走动并重新定义数组......

The difference between creating an array with the implicit array and the array constructor is subtle but important.

When you create an array using

var a = [];

You're telling the interpreter to create a new runtime array. No extra processing necessary at all. Done.

If you use:

var a = new Array();

You're telling the interpreter, I want to call the constructor "Array" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.

You may think "Well, this doesn't matter at all. They're the same!". Unfortunately you can't guarantee that.

Take the following example:

function Array() {
    this.is = 'SPARTA';
}

var a = new Array();
var b = [];

alert(a.is);  // => 'SPARTA'
alert(b.is);  // => undefined
a.push('Woa'); // => TypeError: a.push is not a function
b.push('Woa'); // => 1 (OK)

In the above example, the first call will alert 'SPARTA' as you'd expect. The second will not. You will end up seeing undefined. You'll also note that b contains all of the native Array object functions such as push, where the other does not.

While you may expect this to happen, it just illustrates the fact that [] is not the same as new Array().

It's probably best to just use [] if you know you just want an array. I also do not suggest going around and redefining Array...

绮烟 2024-07-30 21:00:04

有一个重要的区别,但还没有答案提到。

由此看来:

new Array(2).length           // 2
new Array(2)[0] === undefined // true
new Array(2)[1] === undefined // true

您可能会认为 new Array(2) 等同于 [undefined, undefined]但事实并非如此!

让我们尝试一下 <代码>map():

[undefined, undefined].map(e => 1)  // [1, 1]
new Array(2).map(e => 1)            // "(2) [undefined × 2]" in Chrome

看到了吗? 语义完全不同! 那么这是为什么呢?

根据 ES6 Spec 22.1.1.2,Array(len) 的工作只是创建一个新数组,其属性 length 设置为参数 len 就是这样,这意味着这个新创建的数组中没有任何真实元素

函数map(),根据规范22.1.3.15,首先会检查HasProperty,然后调用回调,但事实证明:

new Array(2).hasOwnProperty(0) // false
[undefined, undefined].hasOwnProperty(0) // true

这就是为什么你不能期望任何迭代函数在从 new Array(len) 创建的数组上照常工作。

顺便说一句,Safari 和 Firefox 对于这种情况有更好的“打印”:

// Safari
new Array(2)             // [](2)
new Array(2).map(e => 1) // [](2) 
[undefined, undefined]   // [undefined, undefined] (2) 

// Firefox
new Array(2)             // Array [ <2 empty slots> ]
new Array(2).map(e => 1) // Array [ <2 empty slots> ]
[undefined, undefined]   // Array [ undefined, undefined ]

我已经向 Chromium 提交了一个问题,并要求他们修复这个令人困惑的打印:
https://bugs.chromium.org/p/chromium/issues/detail ?id=732021

更新:它已经修复了。 Chrome 现在打印为:

new Array(2)             // (2) [empty × 2]

There is an important difference that no answer has mentioned yet.

From this:

new Array(2).length           // 2
new Array(2)[0] === undefined // true
new Array(2)[1] === undefined // true

You might think the new Array(2) is equivalent to [undefined, undefined], but it's NOT!

Let's try with map():

[undefined, undefined].map(e => 1)  // [1, 1]
new Array(2).map(e => 1)            // "(2) [undefined × 2]" in Chrome

See? The semantics are totally different! So why is that?

According to ES6 Spec 22.1.1.2, the job of Array(len) is just creating a new array whose property length is set to the argument len and that's it, meaning there isn't any real element inside this newly created array.

Function map(), according to spec 22.1.3.15 would firstly check HasProperty then call the callback, but it turns out that:

new Array(2).hasOwnProperty(0) // false
[undefined, undefined].hasOwnProperty(0) // true

And that's why you can not expect any iterating functions working as usual on arrays created from new Array(len).

BTW, Safari and Firefox have a much better "printing" to this situation:

// Safari
new Array(2)             // [](2)
new Array(2).map(e => 1) // [](2) 
[undefined, undefined]   // [undefined, undefined] (2) 

// Firefox
new Array(2)             // Array [ <2 empty slots> ]
new Array(2).map(e => 1) // Array [ <2 empty slots> ]
[undefined, undefined]   // Array [ undefined, undefined ]

I have already submitted an issue to Chromium and ask them to fix this confusing printing:
https://bugs.chromium.org/p/chromium/issues/detail?id=732021

UPDATE: It's already fixed. Chrome now printed as:

new Array(2)             // (2) [empty × 2]
顾忌 2024-07-30 21:00:04

奇怪的是,在 Chrome 中,new Array(size) 几乎比 [] 快 2 倍,在 FF 和 IE 中也差不多(通过创建和填充数组来衡量)。 仅当您知道数组的大致大小时才重要。 如果添加的项目多于给定的长度,性能提升就会丢失。

更准确地说:Array( 是一种快速恒定时间操作,不分配内存,而 [] 是一种设置类型和值的线性时间操作。

Oddly enough, new Array(size) is almost 2x faster than [] in Chrome, and about the same in FF and IE (measured by creating and filling an array). It only matters if you know the approximate size of the array. If you add more items than the length you've given, the performance boost is lost.

More accurately: Array( is a fast constant time operation that allocates no memory, wheras [] is a linear time operation that sets type and value.

云裳 2024-07-30 21:00:04

有关详细信息,以下页面介绍了为什么你永远不需要使用 new Array()

你永远不需要使用new Object()
JavaScript。 使用对象字面量 {}
反而。 同样,不要使用new Array()
使用数组文字 []
反而。 JavaScript 中的数组工作原理
与 Java 中的数组不同,并且
使用类似 Java 的语法将
让你困惑。

请勿使用新数字新字符串
新布尔值。 这些形式产生
不必要的对象包装。 只需使用
相反,使用简单的文字。

另请查看注释 - new Array(length) 形式没有任何有用的目的(至少在当今的 JavaScript 实现中)。

For more information, the following page describes why you never need to use new Array()

You never need to use new Object() in
JavaScript. Use the object literal {}
instead. Similarly, don’t use new Array(),
use the array literal []
instead. Arrays in JavaScript work
nothing like the arrays in Java, and
use of the Java-like syntax will
confuse you.

Do not use new Number, new String, or
new Boolean. These forms produce
unnecessary object wrappers. Just use
simple literals instead.

Also check out the comments - the new Array(length) form does not serve any useful purpose (at least in today's implementations of JavaScript).

绾颜 2024-07-30 21:00:04

第一个是默认对象构造函数调用。 如果需要,您可以使用它的参数。

var array = new Array(5); //initialize with default length 5

第二个使您能够创建非空数组:

var array = [1, 2, 3]; // this array will contain numbers 1, 2, 3.

The first one is the default object constructor call. You can use it's parameters if you want.

var array = new Array(5); //initialize with default length 5

The second one gives you the ability to create not empty array:

var array = [1, 2, 3]; // this array will contain numbers 1, 2, 3.
一指流沙 2024-07-30 21:00:04

为了更好地理解[]new Array()

> []
  []
> new Array()
  []
> [] == []
  false
> [] === []
  false
> new Array() == new Array()
  false
> new Array() === new Array()
  false
> typeof ([])
  "object"
> typeof (new Array())
  "object"
> [] === new Array()
  false
> [] == new Array()
  false

以上结果来自Windows 7上的Google Chrome控制台。

In order to better understand [] and new Array():

> []
  []
> new Array()
  []
> [] == []
  false
> [] === []
  false
> new Array() == new Array()
  false
> new Array() === new Array()
  false
> typeof ([])
  "object"
> typeof (new Array())
  "object"
> [] === new Array()
  false
> [] == new Array()
  false

The above result is from Google Chrome console on Windows 7.

泅渡 2024-07-30 21:00:04

我可以从这个基于 Fredrik 的好例子的示例开始,以更具体的方式进行解释。

var test1 = [];
test1.push("value");
test1.push("value2");

var test2 = new Array();
test2.push("value");
test2.push("value2");

alert(test1);
alert(test2);
alert(test1 == test2);
alert(test1.value == test2.value);

我刚刚向数组添加了另一个值,并发出了四个警报:
第一个和第二个是给我们存储在每个数组中的值,以确保这些值。 他们将返回相同的!
现在尝试第三个,它返回 false,那是因为

JS 将 test1 视为具有数组数据类型的 VARIABLE,并将 test2 视为具有以下功能的 OBJECT数组的,以及
这里有一些细微的差别。

第一个区别是,当我们调用 test1 时,它会不假思索地调用一个变量,它只返回存储在该变量中的值,而不管其数据类型!
但是,当我们调用 test2 时,它会调用 Array() 函数,然后将我们的 “Pushed” 值存储在其 “Value” 属性中,当我们警告 test2 时,也会发生同样的情况,它返回数组对象的“Value”属性。

因此,当我们检查 test1 是否等于 test2 时,它们当然永远不会返回 true,一个是函数,另一个是变量(具有数组类型),即使它们具有相同的值!

为了确定这一点,请尝试添加 .value 的第四个警报; 它会返回true。 在这种情况下,我们告诉 JS“无论容器的类型是函数还是变量,请比较每个容器中存储的值并告诉我们您看到了什么!” 这正是发生的情况。

我希望我清楚地表达了背后的想法,并为我糟糕的英语感到抱歉。

I can explain in a more specific way starting with this example that's based on Fredrik's good one.

var test1 = [];
test1.push("value");
test1.push("value2");

var test2 = new Array();
test2.push("value");
test2.push("value2");

alert(test1);
alert(test2);
alert(test1 == test2);
alert(test1.value == test2.value);

I just added another value to the arrays, and made four alerts:
The first and second are to give us the value stored in each array, to be sure about the values. They will return the same!
Now try the third one, it returns false, that's because

JS treats test1 as a VARIABLE with a data type of array, and it treats test2 as an OBJECT with the functionality of an array, and
there are few slight differences here.

The first difference is when we call test1 it calls a variable without thinking, it just returns the values that are stored in this variable disregarding its data type!
But, when we call test2 it calls the Array() function and then it stores our "Pushed" values in its "Value" property, and the same happens when we alert test2, it returns the "Value" property of the array object.

So when we check if test1 equals test2 of course they will never return true, one is a function and the other is a variable (with a type of array), even if they have the same value!

To be sure about that, try the 4th alert, with the .value added to it; it will return true. In this case we tell JS "Disregarding the type of the container, whether was it function or variable, please compare the values that are stored in each container and tell us what you've seen!" that's exactly what happens.

I hope I said the idea behind that clearly, and sorry for my bad English.

怀里藏娇 2024-07-30 21:00:04

好吧, var x = new Array()var x = [] 在某些功能上有所不同,我将只解释最有用的两个(在我看来)其中。

在我开始解释这些差异之前,我将首先设定一个基础; 当我们使用 x = [] 定义一个数据类型为 Array 的新变量时,它继承了属于数组原型的所有方法,这与扩展类非常相似(但不完全一样)。 然而,当我们使用 x = new Array() 时,它会初始化分配给变量 x 的数组原型的克隆。

现在让我们看看有什么区别

第一个区别是使用new Array(x)(其中x是一个整数)初始化一个数组< code>x 未定义的值,例如 new Array(16) 将初始化一个包含 16 个项目的数组,所有项目均未定义。 当您异步填充预定义长度的数组时,这非常有用。
例如(再次:))假设您正在获取 100 个竞争对手的结果,并且您从远程系统或数据库异步接收它们,那么您需要在收到后根据排名在数组中分配它们每个结果。 在这种非常罕见的情况下,您将执行类似 myArray[result.rank - 1] = result.name 的操作,因此排名 1 将设置为索引 0,依此类推。

第二个区别是,正如您所知,使用 new Array() 实例化数组原型的全新克隆并将其分配给您的变量,这允许您执行以下操作:一些魔法(顺便说一下,不推荐)。 这个神奇之处在于你可以覆盖遗留数组方法的特定方法。 因此,例如,您可以设置 Array.push 方法将新值推送到数组的开头而不是结尾,并且您还可以向此特定添加新方法(这样更好)数组原型的克隆。 这将允许您使用自己添加的方法在整个项目中定义更复杂的数组类型并将其用作类。

最后一件事,如果您属于极少数关心应用程序的处理开销和内存消耗的人(我真正喜欢的人),那么您永远不会在不绝望的情况下接触 new Array()用它 :)。

我希望这已经足够解释了这个野兽 new Array() :)

Well, var x = new Array() is different than var x = [] is different in some features I'll just explain the most useful two (in my opinion) of them.

Before I get into explaining the differences, I will set a base first; when we use x = [] defines a new variable with data type of Array, and it inherits all the methods that belong to the array prototype, something pretty similar (but not exactly) to extending a class. However, when we use x = new Array() it initilizes a clone of the array prototype assigned to the variable x.

Now let's see what are the difference

The First Difference is that using new Array(x) where x is an integer, initilizes an array of x undefined values, for example new Array(16) will initialize an array with 16 items all of them are undefined. This is very useful when you asynchronously fill an array of a predefined length.
For example (again :) ) let's say you are getting the results of 100 competitiors, and you're receiving them asynchronously from a remote system or db, then you'll need to allocate them in the array according to the rank once you receive each result. In this very rare case you will do something like myArray[result.rank - 1] = result.name, so the rank 1 will be set to the index 0 and so on.

The second difference is that using new Array() as you already know, instanciates a whole new clone of the array prototype and assigns it to your variable, that allows you to do some magic (not recommended by the way). This magic is that you can overwrite a specific method of the legacy array methods. So, for example you can set the Array.push method to push the new value to the beginning of the array instead of the end, and you can also add new methods (this is better) to this specific clone of the Array Prototype. That will allow you to define more complex types of arrays throughout your project with your own added methods and use it as a class.

Last thing, if you're from the very few people (that I truly love) that care about processing overhead and memory consumption of your app, you'd never touch new Array() without being desperate to use it :).

I hope that has explained enough about the beast new Array() :)

大海や 2024-07-30 21:00:04

当您初始化没有任何长度的数组时,没有任何区别。 所以 var a = [] & var b = new Array() 是一样的。

但是如果你用var b = new Array(1);这样的长度初始化数组,它会将数组对象的长度设置为1。所以它相当于var b = []; b.length=1;

每当您执行 array_object.push 时,这都会出现问题,它会在最后一个元素之后添加项目 & 增加长度。

var b = new Array(1);
b.push("hello world");
console.log(b.length); // print 2

var v = [];
a.push("hello world");
console.log(b.length); // print 1

There is no difference when you initialise array without any length. So var a = [] & var b = new Array() is same.

But if you initialise array with length like var b = new Array(1);, it will set array object's length to 1. So its equivalent to var b = []; b.length=1;.

This will be problematic whenever you do array_object.push, it add item after last element & increase length.

var b = new Array(1);
b.push("hello world");
console.log(b.length); // print 2

vs

var v = [];
a.push("hello world");
console.log(b.length); // print 1
吃不饱 2024-07-30 21:00:04

这里面的内容远比表面上看到的还要多。 大多数其他答案都是正确的但也..

new Array(n)

  • 允许引擎为n元素重新分配空间
  • 针对数组创建进行了优化
  • 创建的数组被标记为稀疏,其数组操作性能最低,这是因为每个索引访问都必须检查边界,查看值是否存在并遍历原型链
  • 如果数组被标记为稀疏,则没有回头路(至少在 V8 中),它在其生命周期内总是会变慢,即使您在 1 毫秒或 2 小时后用内容(压缩数组)填充它,也没关系

<代码>[1,2,3]|| []

  • 创建的数组被标记为打包(除非您使用delete[1,,3]语法)
  • 针对数组进行了优化< strong>操作(for ..forEachmap等)
  • 随着数组的增长,引擎需要重新分配空间

可能对于较旧的浏览器版本/浏览器来说并非如此。

There's more to this than meets the eye. Most other answers are correct BUT ALSO..

new Array(n)

  • Allows engine to reallocates space for n elements
  • Optimized for array creation
  • Created array is marked sparse which has the least performant array operations, that's because each index access has to check bounds, see if value exists and walk the prototype chain
  • If array is marked as sparse, there's no way back (at least in V8), it'll always be slower during its lifetime, even if you fill it up with content (packed array) 1ms or 2 hours later, doesn't matter

[1, 2, 3] || []

  • Created array is marked packed (unless you use delete or [1,,3] syntax)
  • Optimized for array operations (for .., forEach, map, etc)
  • Engine needs to reallocate space as the array grows

This probably isn't the case for older browser versions/browsers.

浅暮の光 2024-07-30 21:00:04

第一个是默认的对象构造函数调用。主要用于动态值。

var array = new Array(length); //initialize with default length

创建静态值时使用第二个数组

var array = [red, green, blue, yellow, white]; // this array will contain values.

The first one is the default object constructor call.mostly used for dynamic values.

var array = new Array(length); //initialize with default length

the second array is used when creating static values

var array = [red, green, blue, yellow, white]; // this array will contain values.
没有伤那来痛 2024-07-30 21:00:04

的区别

var arr = new Array(size);

使用Or

arr = [];
arr.length = size;

在这个问题中已经讨论得足够多了。

我想补充一下速度问题 - 当前最快的方法,在 google chrome 上是第二个。

但请注意,这些事情往往会随着更新而发生很大变化。 此外,不同浏览器之间的运行时间也会有所不同。

例如 - 我提到的第二个选项在 chrome 上以 200 万次[操作/秒]运行,但如果您在 mozilla dev. 上尝试它,您会获得了令人惊讶的更高的2300万的比率。

无论如何,我建议您每隔一段时间在不同的浏览器(和机器)上使用网站 这样

The difference of using

var arr = new Array(size);

Or

arr = [];
arr.length = size;

As been discussed enough in this question.

I would like to add the speed issue - the current fastest way, on google chrome is the second one.

But pay attention, these things tend to change a lot with updates. Also the run time will differ between different browsers.

For example - the 2nd option that i mentioned, runs at 2 million [ops/second] on chrome, but if you'd try it on mozilla dev. you'd get a surprisingly higher rate of 23 million.

Anyway, I'd suggest you check it out, every once in a while, on different browsers (and machines), using site as such

謸气贵蔟 2024-07-30 21:00:04

据我所知,您可以找到切片(或数组的其他功能),例如code1。和code2显示您Array和他的< em>实例:

代码1:

[].slice; // find slice here
var arr = new Array();
arr.slice // find slice here
Array.prototype.slice // find slice here

代码2:

[].__proto__ == Array.prototype; // true
var arr = new Array();
arr.__proto__ == Array.prototype; // true

结论:

正如你所看到的[]和< code>new Array() 创建一个新的 Array 实例。它们都从 Array.prototype 获取原型函数,

它们只是 Array 的不同实例。所以这解释了为什么
[] != []

:)

As I know the diference u can find the slice(or the other funcitons of Array) like code1.and code2 show u Array and his instances:

code1:

[].slice; // find slice here
var arr = new Array();
arr.slice // find slice here
Array.prototype.slice // find slice here

code2:

[].__proto__ == Array.prototype; // true
var arr = new Array();
arr.__proto__ == Array.prototype; // true

conclusion:

as u can see [] and new Array() create a new instance of Array.And they all get the prototype functions from Array.prototype

They are just different instance of Array.so this explain why
[] != []

:)

拧巴小姐 2024-07-30 21:00:04

没有什么大的区别,它们基本上做同样的事情,但是以不同的方式做,但是请继续阅读,看看 W3C 的这个声明:

var cars = ["Saab", "Volvo","BMW"];

var cars = new Array("Saab", "Volvo", "BMW");

上面的两个例子的作用完全相同。 没有必要使用
新数组()。
为了简单性、可读性和执行速度,请使用
第一个(数组文字方法)。

但与此同时,使用 new Array 语法创建新数组被认为是一种不好的做法:

避免使用 new Array()

无需使用 JavaScript 的内置数组构造函数
新数组()。
请使用 [] 代替。
这两个不同的语句都创建一个名为的新空数组
点:

var points = new Array();         // Bad
var points = [];                  // Good 

这两个不同的语句都创建一个包含 6 的新数组
数字:

var points = new Array(40, 100, 1, 5, 25, 10); // Bad    
var points = [40, 100, 1, 5, 25, 10];          // Good

new 关键字只会使代码变得复杂。 它还可以产生一些
意想不到的结果:

var points = new Array(40, 100);  // Creates an array with two elements (40 and 100)

如果我删除其中一个元素会怎样?

var points = new Array(40);       // Creates an array with 40 undefined elements !!!!!

所以基本上不被认为是最佳实践,也有一个细微的差别,你可以像这样将长度传递给 new Array(length) ,这也不是推荐的方式。

There is no big difference, they basically do the same thing but doing them in different ways, but read on, look at this statement at W3C:

var cars = ["Saab", "Volvo","BMW"];

and

var cars = new Array("Saab", "Volvo", "BMW");

The two examples above do exactly the same. There is no need to use
new Array().
For simplicity, readability and execution speed, use the
first one (the array literal method).

But at the same time, creating new array using new Array syntax considered as a bad practice:

Avoid new Array()

There is no need to use the JavaScript's built-in array constructor
new Array().
Use [] instead.
These two different statements both create a new empty array named
points:

var points = new Array();         // Bad
var points = [];                  // Good 

These two different statements both create a new array containing 6
numbers:

var points = new Array(40, 100, 1, 5, 25, 10); // Bad    
var points = [40, 100, 1, 5, 25, 10];          // Good

The new keyword only complicates the code. It can also produce some
unexpected results:

var points = new Array(40, 100);  // Creates an array with two elements (40 and 100)

What if I remove one of the elements?

var points = new Array(40);       // Creates an array with 40 undefined elements !!!!!

So basically not considered as the best practice, also there is one minor difference there, you can pass length to new Array(length) like this, which also not a recommended way.

白衬杉格子梦 2024-07-30 21:00:04

我使用 [] 发生了奇怪的行为。

我们有模型“类”,其字段初始化为某个值。 例如:

require([
  "dojo/_base/declare",
  "dijit/_WidgetBase",
], function(declare, parser, ready, _WidgetBase){

   declare("MyWidget", [_WidgetBase], {
     field1: [],
     field2: "",
     function1: function(),
     function2: function()
   });    
});

我发现当字段用 [] 初始化时,它将被所有模型对象共享。 对其中一项的更改会影响所有其他项。

使用 new Array() 初始化它们时不会发生这种情况。 对象的初始化也是如此({} 与 new Object()

TBH 我不确定这是否是我们使用的框架的问题(Dojo

I've incurred in a weird behaviour using [].

We have Model "classes" with fields initialised to some value. E.g.:

require([
  "dojo/_base/declare",
  "dijit/_WidgetBase",
], function(declare, parser, ready, _WidgetBase){

   declare("MyWidget", [_WidgetBase], {
     field1: [],
     field2: "",
     function1: function(),
     function2: function()
   });    
});

I found that when the fields are initialised with [] then it would be shared by all Model objects. Making changes to one affects all others.

This doesn't happen initialising them with new Array(). Same for the initialisation of Objects ({} vs new Object())

TBH I am not sure if its a problem with the framework we were using (Dojo)

昔日梦未散 2024-07-30 21:00:04

我在使用 Promise 时发现了差异。 在使用 Promise 数组(比如 arr,初始化为 arr=[])时,在 Promise.all(arr) 中出现错误。 而当声明为 arr = Array() 时,没有出现编译问题。 希望这可以帮助。

I found a difference while using promises. While using array of promises (say arr, initialised as arr=[]), got an error in Promise.all(arr). Whereas when declared as arr = Array(), did not get compilation issues. Hope this helps.

情深如许 2024-07-30 21:00:04

请记住:

使用 new 或跳过它,不会对代码的功能产生影响。

考虑这个例子:

const x = Array(1, 2, 3); //an array defined simply
const y = new Array(1, 2, 3); // an array defined with new keyword

 
console.log(x); // output: [1, 2, 3]
console.log(y); // output: [1, 2, 3]


console.log(x.length);  // output: 3
console.log(y.length);  // output: 3

使用理由:

  • 新的 new Array() 比 Array() 多做一件事:你可以将一个数字传递给构造函数,然后你将得到一个该长度的数组
var myArray = new Array(); // some output
var myArray = []; // will return te same output as above

  • 使用此方法的另一个优点是它预先在堆栈中创建所需大小的数组

不使用的原因:新

- 避免额外的编码,因为有时代码几乎成为同义词。

希望能帮助到你。

Keep in mind:

Work with new or skip it, there will be no effect on the functioning of the code.

Consider this example:

const x = Array(1, 2, 3); //an array defined simply
const y = new Array(1, 2, 3); // an array defined with new keyword

 
console.log(x); // output: [1, 2, 3]
console.log(y); // output: [1, 2, 3]


console.log(x.length);  // output: 3
console.log(y.length);  // output: 3

Reasons to Use: New

  • the new Array() does One more thing then Array() : You can pass a number to the constructor, and you will get an array of that length.

var myArray = new Array(); // some output
var myArray = []; // will return te same output as above

  • Another advantage of using this method is that it creates the required size of the array beforehand in the stack.

Reason not to use: New

-Avoid the extra coding, as sometimes code becomes virtually synonymous.

Hope it helps.

水波映月 2024-07-30 21:00:04

我发现这两种结构之间的一个差异让我很痛苦。

假设我有:

function MyClass(){
  this.property1=[];
  this.property2=new Array();
};
var MyObject1=new MyClass();
var MyObject2=new MyClass();

在现实生活中,如果我这样做:

MyObject1.property1.push('a');
MyObject1.property2.push('b');
MyObject2.property1.push('c');
MyObject2.property2.push('d');

我最终得到的是这样的:

MyObject1.property1=['a','c']
MyObject1.property2=['b']
MyObject2.property1=['a','c']
MyObject2.property2=['d']

我不知道语言规范所说的应该发生什么,但是如果我希望我的两个对象在我的对象,我必须使用new Array()

I've found one difference between the two constructions that bit me pretty hard.

Let's say I have:

function MyClass(){
  this.property1=[];
  this.property2=new Array();
};
var MyObject1=new MyClass();
var MyObject2=new MyClass();

In real life, if I do this:

MyObject1.property1.push('a');
MyObject1.property2.push('b');
MyObject2.property1.push('c');
MyObject2.property2.push('d');

What I end up with is this:

MyObject1.property1=['a','c']
MyObject1.property2=['b']
MyObject2.property1=['a','c']
MyObject2.property2=['d']

I don't know what the language specification says is supposed to happen, but if I want my two objects to have unique property arrays in my objects, I have to use new Array().

淤浪 2024-07-30 21:00:04

使用 Array 构造函数创建一个所需长度的新数组,并用未定义的值填充每个索引,将数组分配给变量 one 会创建您为其提供信息的索引。

Using the Array constructor makes a new array of the desired length and populates each of the indices with undefined, the assigned an array to a variable one creates the indices that you give it info for.

浅忆流年 2024-07-30 21:00:03

有区别,但在该示例中没有区别。

使用更详细的方法:new Array() 在参数中确实有一个额外的选项:如果将一个数字传递给构造函数,您将获得一个该长度的数组:

x = new Array(5);
alert(x.length); // 5

为了说明不同的方法创建数组:

var a = [],            // these are the same
    b = new Array(),   // a and b are arrays with length 0

    c = ['foo', 'bar'],           // these are the same
    d = new Array('foo', 'bar'),  // c and d are arrays with 2 strings

    // these are different:
    e = [3]             // e.length == 1, e[0] == 3
    f = new Array(3),   // f.length == 3, f[0] == undefined

;

另一个区别是,使用 new Array() 时,您可以设置数组的大小,这会影响堆栈大小。 如果您遇到堆栈溢出(Array.push 与 Array.unshift 的性能)(发生这种情况),这可能会很有用当数组的大小超过堆栈的大小时,必须重新创建数组。 因此,根据用例,使用 new Array() 时实际上可以提高性能,因为可以防止溢出的发生。

正如这个答案中指出的,new Array(5)实际上不会添加五个未定义项添加到数组中。 它只是增加了五个项目的空间。 请注意,以这种方式使用Array会使依赖array.length进行计算变得困难。

There is a difference, but there is no difference in that example.

Using the more verbose method: new Array() does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:

x = new Array(5);
alert(x.length); // 5

To illustrate the different ways to create an array:

var a = [],            // these are the same
    b = new Array(),   // a and b are arrays with length 0

    c = ['foo', 'bar'],           // these are the same
    d = new Array('foo', 'bar'),  // c and d are arrays with 2 strings

    // these are different:
    e = [3]             // e.length == 1, e[0] == 3
    f = new Array(3),   // f.length == 3, f[0] == undefined

;

Another difference is that when using new Array() you're able to set the size of the array, which affects the stack size. This can be useful if you're getting stack overflows (Performance of Array.push vs Array.unshift) which is what happens when the size of the array exceeds the size of the stack, and it has to be re-created. So there can actually, depending on the use case, be a performance increase when using new Array() because you can prevent the overflow from happening.

As pointed out in this answer, new Array(5) will not actually add five undefined items to the array. It simply adds space for five items. Be aware that using Array this way makes it difficult to rely on array.length for calculations.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文