Javascript find()方法正在使我的函数崩溃

Javascript find()方法正在使我的函数崩溃,javascript,node.js,reactjs,typescript,function,Javascript,Node.js,Reactjs,Typescript,Function,当我发送一个在我的对象中不可用的数字时,我试图找出如何使我的函数返回false const getUnitColor = (unitNumber: any): any => { const color = getColor.unit.find((unit: any) => { return unit.number === parseInt(unitNumber); }).unitColor[0].color; if (color) {

当我发送一个在我的对象中不可用的数字时,我试图找出如何使我的函数返回false

 const getUnitColor = (unitNumber: any): any => {
    const color = getColor.unit.find((unit: any) => {
      return unit.number === parseInt(unitNumber);
    }).unitColor[0].color;
    if (color) {
      return '#' + color;
    } else {
      return false;
    }
  };
  
  console.log(getUnitColor("1"))

  console.log(getUnitColor("0")) // should return false
我在第二个控制台日志中遇到的错误是UncaughtTypeError:无法读取undefined的属性“unitColor”,因为它应该返回false

JS Fiddle有我正在传递的一个示例数据 您可以使用

或者指定find的结果并返回值

const color = getColor.unit.find((unit: any) => {
  return unit.number === parseInt(unitNumber);
});

if (color) {
  return '#' + color.unitColor[0].color;
} else {
  return false;
}
你可以使用

或者指定find的结果并返回值

const color = getColor.unit.find((unit: any) => {
  return unit.number === parseInt(unitNumber);
});

if (color) {
  return '#' + color.unitColor[0].color;
} else {
  return false;
}
希望这能奏效:

const getUnitColor = (unitNumber) => {
    const foundColor = getColor.unit.find(function(unit){
      return unit.number === parseInt(unitNumber);
    })
    if (foundColor) {
      return '#' + foundColor.unitColor[0].color;
    } else {
      return false;
    }
 }
希望这能奏效:

const getUnitColor = (unitNumber) => {
    const foundColor = getColor.unit.find(function(unit){
      return unit.number === parseInt(unitNumber);
    })
    if (foundColor) {
      return '#' + foundColor.unitColor[0].color;
    } else {
      return false;
    }
 }