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();