补充记录一下,有些方法很须要熟练记忆的javascript
JSON对象对值有严格的规定java
复合类型的值只能是数组或对象,不能是函数、正则表达式对象、日期对象。
原始类型的值只有四种:字符串、数值(必须以十进制表示)、布尔值和null(不能使用NaN, Infinity, -Infinity和undefined)。
字符串必须使用双引号表示,不能使用单引号。
对象的键名必须放在双引号里面。
数组或对象最后一个成员的后面,不能加逗号。
我对这段话的理解是:正则表达式
该方法用来将参数值转化为JSON字符串数组
JSON.stringify("javascript"); //"javascript"
参数类型为number函数
console.log(JSON.stringify(1)); // 1 console.log(JSON.stringify(0XFFF)); //4095 console.log(JSON.stringify(Infinity)); //null console.log(JSON.stringify(NaN)); //null
参数类型boolprototype
console.log(JSON.stringify(false)); //false console.log(JSON.stringify(true)); //true
JSON.stringify("null"); //null
参数类型数组code
JSON.stringify([1,null,NaN,undefined,function () {},(new Date()),,]); // [1,null,null,null, null, "2018-11-02T15:22:53.482Z", null]
注意空位会返回nullxml
参数类型对象对象
console.log(JSON.stringify({"a":1,"b":undefined})); //{"a":1} 忽略undefined键值 console.log(JSON.stringify({"a":null,"b":NaN})); //{"a":null,"b":null} NaN与Infinity返回null console.log(JSON.stringify({"a":function () {},"b":(new Date())})); //{"b":"2018-11-02T15:27:13.886Z"} 忽略undefined键值
当对象中有不可遍历属性时,跳过该属性ip
它的第二个参数可填入数组或者函数
参数为数组时,仅适用于第一个参数为对象时才有效;其对象包括数组
起到过滤的效果,留咱们本身想要的键值对
console.log(JSON.stringify({a : 1, b : 2}, ["b"])); //{b : 2}
参数为函数:
JSON.stringify({ a: 1, b: [1, 2] }, (key, value) => { console.log(key + ":" + value); return value; }); /* :[object Object] a:1 b:1,2 0:1 1:2 */
由例子能够看出,一共执行了5次
第一次执行将参数总体做为value,key为空;
剩余每次都按更加value的值进行下一次执行;
若value为对象,会执行完对象中的第一个成员,再去执行第二个成员,直到没有value
返回值,我认为它是经过value把参数遍历一遍,将value填入相应位置,将其返回
JSON.stringify()正是调用了toJSON方法;因此对其进行改造能够改变输出
例如当参数为正则时,会返回空对象
JSON.stringify(/aa/) // {} RegExp.prototype.toJSON = RegExp.prototype.toString; JSON.stringify(/aa/) // "/aa/"
该方法则是将JSON.stringify()生成的结果还原
JSON.parse(JSON.stringify("123")); //123 JSON.parse(JSON.stringify(undefined)); //报错不是JSON对象