JavaScript Patterns 3.4 Array Literal
2014-05-30 23:03 小郝(Kaibo Hao) 阅读(446) 评论(0) 编辑 收藏 举报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 element var a = [3]; console.log(a.length); // 1 console.log(a[0]); // 3 // an array of three elements var a = new Array(3); console.log(a.length); // 3 console.log(typeof a[0]); // "undefined" // using array literal var a = [3.14]; console.log(a[0]); // 3.14 var a = new Array(3.14); // RangeError: invalid array length console.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 object Array.isArray({ length: 1, "0": 1, slice: function () {} }); // false if (typeof Array.isArray === "undefined") { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) === "[object Array]"; }; }
作者:小郝
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。