Skip to content

Instantly share code, notes, and snippets.

@Yang03
Created July 28, 2017 03:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yang03/a47317babadcaa20aca2ddedfaaf3e6d to your computer and use it in GitHub Desktop.
Save Yang03/a47317babadcaa20aca2ddedfaaf3e6d to your computer and use it in GitHub Desktop.
JSON.stringify() function
var obj = {a: 1, b:2}
console.log(JSON.stringify(obj)) // {"a":1,"b":1}
var obj1 = {
a:1,
b: function() {
console.log(1)
},
c: undefined
}
// 不会输出c,b
console.log(JSON.stringify(obj1)) // {"a":1}
//JSON.stringify(value [, replacer [, space]])
/*
replacer 接受一个函数,每个属性都会过滤一变
space 格式化
*/
var replacer = function (k, v) {
if (v == undefined) {
return 'undefined'
}
if (typeof v === 'function') {
return Function.prototype.toString.call(v)
}
return v
}
var obj1 = {
a:1,
b: function() {
console.log(1)
},
c: undefined
}
console.log(JSON.stringify(obj1,replacer)) // {"a":1,"b":"function () {\n console.log(1)\n }","c":"undefined"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment