gpt4 book ai didi

javascript - 数组中的函数在js中为空

转载 作者:行者123 更新时间:2023-11-30 09:40:16 25 4
gpt4 key购买 nike

我在用数组编写函数时遇到问题。

这是发生了什么:

config.js

module.exports = {
transformers: {
reshape: {
parser: 'sugarml',
plugins: [
// require('reshape-custom-elements')({defaultTag: 'span'})
function () {
console.log(arguments)
}
]
}
}
}

然后在 Node 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).

source

我会质疑在 JSON 中存储这样的配置,但如果你真的需要你可以考虑像 serialize-javascript 这样的东西它将处理函数的序列化。

关于javascript - 数组中的函数在js中为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41434650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com