《JavaScript模式》一书中提到的一些坑

1. 应当用数组字面量来创建数组,而不是用new Array()


 

1         //反模式
2         var a = new Array('itsy', 'bitsy', 'spider');
3 
4         //用字面量
5         var a = ['itsy', 'bitsy', 'spider'];
6         console.log(typeof a);                  //object
7         console.log(a.constructor === Array);   //true

  说明:对象的constructor属性引用了该对象的构造函数

1         console.log((function(){}).constructor);    //function Function() { [native code] }
2         console.log({}.constructor);                //function Object() { [native code] }
3         console.log('string'.constructor);          //function String() { [native code] }
4         var i=0;
5         console.log(i.constructor);                 //function Number() { [native code] }
6         var a = true;
7         console.log(a.constructor);                 //function Boolean() { [native code] }

  避免new Array()的另一个理由是用于避免构造函数中可能产生的陷阱——当向Array()构造函数传递单个数字时,它并不会成为第一个数组元素的值,而是设定了数组的长度。

1         var a = [3];            
2         console.log(a.length);  //1
3         console.log(a[0]);      //3
4 
5         var b = new Array(3);
6         console.log(b.length);  //3
7         console.log(b[0]);      //undefined

  当向new Array()中传递一个浮点数时,会直接报错

1         var a = [3.14];
2         console.log(a[0]);      //3.14
3         
4         var b = new Array(3.14);    //报错:test.html:377 Uncaught RangeError: Invalid array length

  传入多个数则可以:

1         var b = new Array(1,2);
2         console.log(b[0]);          //1

  总之,看起来使用数组字面量更靠谱一点

2. JSON和字面量的区别


 

  在JSON中,属性名称需要包装在引号里

  而在对象字面量中,仅当属性名不是有效表示符时才需要引号 比如属性名字符之间有空格 {"first name": "Dave"}

  此外,在JSON字符串中,不能使用函数或正则表达式字面量。

3. 使用JSON


 

  不推荐使用eval()对任意JSON字符串进行求值,推荐使用JSON.parse()方法进行解析。

1         var js = '{"mykey" : "my value"}';
2 
3         //反模式
4         var data = eval('(' + js + ')');
5 
6         //应该使用
7         var data = JSON.parse(js);
8         console.log(data.mykey);        //my value
9     

//jQuery中:
var data = jQuery.parseJSON(js);

  相对的方法----序列化为JSON字符串:JSON.stringify(data)

原文地址:https://www.cnblogs.com/haoyijing/p/5768393.html