为什么不能对函数表达式进行字符串化?

wwa*_*waw 13 javascript json function stringification

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

console.log(JSON.stringify(function(){console.log('foobar');}));
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 29

JSON根本无法对函数进行字符串化,它只是处理它们undefined或者像null值一样处理它们.您可以在EcmaScript5.1§15.12.3中查看确切的算法,请参阅MDN上说明.

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

console.log("" + function(){console.log('foobar');})
Run Code Online (Sandbox Code Playgroud)


aur*_*raz 6

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


Que*_*tin 5

JSON无法表示函数.它是一种数据格式,旨在简化和跨语言兼容(而且功能是最后一种跨语言兼容的功能).

来自JSON.stringify的文档:

如果在转换期间遇到未定义,函数或XML值,则将其省略(当在对象中找到它时)或者删除为null(当它在数组中找到时).


Vid*_*dar 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))
Run Code Online (Sandbox Code Playgroud)

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

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