24

为什么这不会产生任何东西?

console.log(JSON.stringify(function(){console.log('foobar');}));
4

6 回答 6

38

JSON 根本无法对函数进行字符串化,它就像undefinednull值一样处理它们。您可以在EcmaScript 5.1 §15.12.3中检查确切的算法,另请参阅MDN 上的描述

但是,您当然可以通过将函数表达式转换为字符串来对函数表达式进行字符串化,尝试

console.log("" + function(){console.log('foobar');})
于 2012-09-29T10:37:42.150 回答
8

yourFunctionName.toString();还将字符串化一个函数

于 2019-08-28T14:23:10.813 回答
7

JSON 无法表示函数。它是一种数据格式,旨在实现跨语言的简单性和兼容性(函数是跨语言兼容的最后一件事)。

来自JSON.stringify的文档:

如果在转换过程中遇到未定义、函数或 XML 值,则它要么被忽略(当它在对象中找到时),要么被审查为 null(当它在数组中找到时)。

于 2012-09-29T10:37:56.340 回答
5

如果您还想用于JSON.stringify转换函数和本机对象,则可以将转换器函数作为第二个参数传递:

const data = {
  fn: function(){}
}

function converter(key, val) {
  if (typeof val === 'function' || val && val.constructor === RegExp) {
    return String(val)
  }
  return val
}

console.log(JSON.stringify(data, converter, 2))

undefined如果要省略结果,请从转换器函数返回。

第三个参数是您希望输出缩进多少个空格(可选)。

于 2019-08-29T12:13:09.110 回答
3

您不能这样做,但有一些第三方库可以帮助您做到这一点,例如:https ://www.npmjs.com/package/json-fn

于 2017-03-13T06:38:55.420 回答
0

有几种方法可以做到这一点。

假设你有函数 foo

> function (foo) { return foo}

如果您控制台记录它,它会返回带有类型的函数名称

> console.log(foo)
[Function: foo]

当要访问它的字符串化版本时,您可以使用下面列出的方法之一。

> console.log(`${foo}`)
function (bar) { return bar}
undefined
> console.log(foo.toString())
function (bar) { return bar}
undefined
> console.log("" + foo)
function (bar) { return bar}
undefined
于 2021-08-13T00:19:22.080 回答