首页 > 解决方案 > 检查数组是否包含对象时函数未输出正确的值

问题描述

我犯了什么错误?

let array1= [
  {no: 1, names: "beef", from: "cow", price: 5},
  {no: 2, names: "pork", from: "pig", price: 10},
];

function printByNames(a) {
  if (array1.includes(a) == false) {
    return (a + " is not a meat!");
  } else {
    return array1.filter(function (object) {
        return console.log(object.names == a);
    })[0];
  }
}

//test in console = false when should return object.
printByNames("beef")

如果名称在数组中,该函数应该 console.log 整个对象。如果不是,它应该返回输入 + 字符串“不是肉”。

标签: javascriptarraysfunction

解决方案


你可以像这样得到对象

let array1= [
    {no: 1, names: "beef", from: "cow", price: 5},
    {no: 2, names: "pork", from: "pig", price: 10},
  ];

  function printByNames(a) {
    var arrayobject =  array1.find(function (object) {
          return object.names == a;
      });

      return arrayobject ? arrayobject : 'a is not a meat!'
  }
  printByNames("beef")

推荐阅读