首页 > 网站 > WEB开发 > 正文

JavaScript Patterns 3.4 Array Literal

2024-04-27 14:23:15
字体:
来源:转载
供稿:网友

javaScript Patterns 3.4 Array Literal

2014-05-30 23:03 by 小郝(Kaibo Hao), ... 阅读, ... 评论, 收藏, 编辑

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]";    };} 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表