检查数组是否包含对象时函数未输出正确的值

时间:2019-10-15 13:33:10

标签: javascript arrays function

我犯了什么错误?

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记录整个对象。如果不是,则应返回输入+字符串“不是肉”。

2 个答案:

答案 0 :(得分:1)

您可以得到这样的对象

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")

答案 1 :(得分:0)

您可以找到带有所需名称的对象,然后检查是否有对象。

function printByName(name) {
    var object = array1.find(object => object.name === name);
    if (!object) return name + " is not a meat!";
    return object;
}

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

console.log(printByName("beef"));
console.log(printByName("fish"));