控制台.log不输出 json



var _json = [{"codigo": "1", "nome": "Robert Santos", "turma": "EM2A"}, {"codigo": "2", "nome": "Eduardo Alves Silveira", "turma": "EM3A"}, {"codigo": "3", "nome": "Amara Gouveia", "turma": "EMT2B"}, {"codigo": "4", "nome": "Tainá Belchior da Silva", "turma": "EF5B"}];
function console() {
console.log(JSON.stringify(_json, null, 4));
}
console();

嗨,我正在使用此代码,但是当我尝试执行console()时,出现此错误:TypeError: console.log is not a function

我应该怎么做才能解决这个问题?

你之所以TypeError: console.log is not a function,是因为你在全局范围内用自己的函数覆盖了console对象,该函数名为console,该函数没有log函数。您可以通过将函数重命名为其他名称来解决此问题,代码片段示例:

var _json = [{"codigo": "1","nome": "Robert Santos","turma": "EM2A"}, 
{"codigo": "2","nome": "Eduardo Alves Silveira","turma": "EM3A"},{"codigo": 
"3","nome": "Amara Gouveia","turma": "EMT2B"},{"codigo": "4","nome": "Tainá Belchior da Silva","turma": "EF5B"}];
function log() {
console.log(JSON.stringify(_json, null, 4));
}
log();

全局window对象已经有一个名为console的函数,您正在尝试用自己的console函数覆盖该函数。 只需将console函数重命名为其他名称即可。

不能将函数命名为console

原因-Console是 JavaScript 中的现有对象,用于提供对浏览器调试控制台的访问。阅读 MDN 网络文档以了解更多信息

更正的代码

var _json = [{"codigo": "1","nome": "Robert Santos","turma": "EM2A"}, 
{"codigo": "2","nome": "Eduardo Alves Silveira","turma": "EM3A"},{"codigo": 
"3","nome": "Amara Gouveia","turma": "EMT2B"},{"codigo": "4","nome": "Tainá Belchior da Silva","turma": "EF5B"}];
function logger() {
console.log(JSON.stringify(_json, null, 4));
}
logger();

相关内容

  • 没有找到相关文章

最新更新