admin管理员组文章数量:1180482
As the title says: What is the difference between condensed arrays and literal arrays?
new Array("John", "Bob", "Sue"); // condensed array
["John", "Bob", "Sue"]; // literal array
Are there things I can do with one that I can't do with the other? Or is it the way it is kept in the memory?
As the title says: What is the difference between condensed arrays and literal arrays?
new Array("John", "Bob", "Sue"); // condensed array
["John", "Bob", "Sue"]; // literal array
Are there things I can do with one that I can't do with the other? Or is it the way it is kept in the memory?
Share Improve this question edited Sep 17, 2011 at 4:27 Ray Toal 88.4k20 gold badges184 silver badges243 bronze badges asked Sep 17, 2011 at 4:25 TCSTCS 5,8906 gold badges58 silver badges92 bronze badges 1- I'd guess it's just two syntaxes for the same thing – Daniel Commented Sep 17, 2011 at 4:28
3 Answers
Reset to default 28No, there is no difference in the produced object, they are the same.
The first is an attempt to satisfy programmers that are use to a "classical" environment where you have to instantiate a "new" Array object.
It should be noted that Arrays in javascript are not a sequential allocation of memory, but objects with enumerable property names and a few extra (useful) methods.
Because of this creating an array of a set length is fairly useless and unnecessary in most (if not all) cases.
var array = new Array(10);
is functionally the same is manually setting the length of your array
var array = [];
array.length = 10;
There is at least one well known use of the Array() constructor:
String.prototype.repeat= function(n){
n= n || 1;
return Array(n+1).join(this);
}
document.writeln('/'.repeat(80))
The semantics of the array initialiser is in section 11.1.4 of the ECMA 262 5th edition spec. You can read it there. It says that the meaning of the initialiser is the same as if new Array
were called. But there is one thing you can do with initialiser that you cannot with the constructor. Check this out:
> a = [3,,,,5,2,3]
3,,,,5,2,3
> a = new Array(3,,,,5,2,3)
SyntaxError: Unexpected token ,
I used in the initialiser what is known as an "elision".
The array constructor has a bit of flexibility of its own
a = new Array(10)
,,,,,,,,,
a = new Array(1,2,30)
1,2,30
So a single argument to the constructor produces an array of that many undefineds.
本文标签: javascriptWhat is the difference between condensed arrays and literal arraysStack Overflow
版权声明:本文标题:javascript - What is the difference between condensed arrays and literal arrays? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738157677a2066446.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论