数组中的函数在js中为空
Function in array is null in js
我在数组中编写函数时遇到问题。
事情是这样的:
config.js
module.exports = {
transformers: {
reshape: {
parser: 'sugarml',
plugins: [
// require('reshape-custom-elements')({defaultTag: 'span'})
function () {
console.log(arguments)
}
]
}
}
}
然后在节点REPL
var config = require('./config.js')
console.log(JSON.stringify(config.transformers, null, 2))
输出
{
"reshape": {
"parser": "sugarml",
"plugins": [
null
]
},
"uglify-js": {
"mangle": {
"toplevel": true
}
},
"rollup": {
"format": "es",
"plugins": {
"rollup-plugin-node-resolve": {},
"rollup-plugin-commonjs": {}
}
}
}
我很困惑为什么 plugins
是 [null]
您不能序列化 JSON 中的函数。来自 MDN:
If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). JSON.stringify can also just return undefined when passing in "pure" values like JSON.stringify(function(){}) or JSON.stringify(undefined).
我会质疑在 JSON 中存储这样的配置,但是如果您 真的 需要,您可以考虑像 serialize-javascript 这样的东西来处理序列化功能。
我在数组中编写函数时遇到问题。
事情是这样的:
config.js
module.exports = {
transformers: {
reshape: {
parser: 'sugarml',
plugins: [
// require('reshape-custom-elements')({defaultTag: 'span'})
function () {
console.log(arguments)
}
]
}
}
}
然后在节点REPL
var config = require('./config.js')
console.log(JSON.stringify(config.transformers, null, 2))
输出
{
"reshape": {
"parser": "sugarml",
"plugins": [
null
]
},
"uglify-js": {
"mangle": {
"toplevel": true
}
},
"rollup": {
"format": "es",
"plugins": {
"rollup-plugin-node-resolve": {},
"rollup-plugin-commonjs": {}
}
}
}
我很困惑为什么 plugins
是 [null]
您不能序列化 JSON 中的函数。来自 MDN:
If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). JSON.stringify can also just return undefined when passing in "pure" values like JSON.stringify(function(){}) or JSON.stringify(undefined).
我会质疑在 JSON 中存储这样的配置,但是如果您 真的 需要,您可以考虑像 serialize-javascript 这样的东西来处理序列化功能。