Array Literal Syntax
To avoid potential errors when creating dynamic arrays at runtime, it's much safer to stick with the array literal notation.
Array Constructor Curiousness
When you pass a single number to the Array() constructor, it doesn't become the value of the first array element.
// an array of one elementvar a = [3];console.log(a.length); // 1console.log(a[0]); // 3// an array of three elementsvar a = new Array(3);console.log(a.length); // 3console.log(typeof a[0]); // "undefined"// using array literalvar a = [3.14];console.log(a[0]); // 3.14var a = new Array(3.14); // RangeError: invalid array lengthconsole.log(typeof a); // "undefined"
Clever uses of the Array() constructor
var white = new Array(256).join(' ');
Check for Array-ness
Array.isArray([]); // true// trying to fool the check with an array-like objectArray.isArray({ length: 1, "0": 1, slice: function () {}}); // falseif (typeof Array.isArray === "undefined") { Array.isArray = function (arg) { return Object.PRototype.toString.call(arg) === "[object Array]"; };}
新闻热点
疑难解答