What is the difference between condensed arrays and literal arrays?
As the title says: What is the difference between condensed arrays and literal arrays?
new 开发者_StackOverflow中文版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?
No, 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.
精彩评论