数组中的函数在js中为null

我在编写数组中的函数时遇到了麻烦。

这是发生了什么事情:

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:

如果未定义,则在转换过程中遇到函数或符号时,会将其忽略(在对象中find该对象时)或将其检查为空(在数组中find它时)。 JSON.stringify也可以在传递“纯”值(如JSON.stringify(function(){})或JSON.stringify(undefined)时返回undefined。

资源

我会问这样的存储在JSONconfiguration,但如果你真的需要你可以考虑像serialize-javascript将处理function的序列化。