为什么当我控制台.log(createdAnimal)时未定义

Why when I get undefined when I console.log(createdAnimal)?

本文关键字:createdAnimal 未定义 log 控制台 为什么      更新时间:2023-09-26

我试图在这段代码中实现的是能够控制台.log(createdAnimal),然后获得打印出带有以下参数的objectAnimal的代码:

animalMaker('cat','flying',true);

它在我调用animalMaker函数时工作,但我需要它在console.log(createdAnimal).时工作

提前谢谢!

这是代码:

function animalMaker(inputType, inputSuperPower, inputCanFly){
  var objectAnimal = {
    'type': inputType,
    'inputSuperPower': inputSuperPower,
    'inputCanFly': inputCanFly,
    'createdBy': 'Scotty'
  };
  console.log(objectAnimal)
}
var createdAnimal = animalMaker('cat','flying',true); 
console.log(createdAnimal);

您需要从函数返回对象:

function animalMaker(inputType, inputSuperPower, inputCanFly){
  var objectAnimal = {
    'type': inputType,
    'inputSuperPower': inputSuperPower,
    'inputCanFly': inputCanFly,
    'createdBy': 'Scotty'
  };
  return objectAnimal;
}

到目前为止,animalMaker函数不返回任何内容,当不返回值时,函数将默认返回javascript中的undefined
因此,当使用animalMaker函数返回的值设置变量时,该值将为undefined

要将createdAnimal变量设置为objectAnimal的值,您需要从函数中返回它。通过用返回语句结束animalMaker函数:

return objectAnimal;  

记住,函数子句中返回语句之后的代码永远不会被执行,return结束函数:

function example() {
    return true;
    console.log('This will never be printed');
}