在数组中搜索对象

时间:2019-04-17 07:40:15

标签: javascript arrays methods

该函数必须将汽车品牌作为第二个参数。如果未找到mark,则应显示消息“ car sold”。如果找到品牌,它应该显示您要寻找的汽车的对象。怎么了

const arr = [{
    "mark": "BMW",
    "price": "55 000",
    "color": "red",
    "constructor": "Billy%Zekun",
    "country": "Germany",
    "certificate": "yes"
  },
  {
    "mark": "Mercedes-benz",
    "price": "63 000",
    "color": "blue",
    "constructor": "Jon%Adams",
    "country": "Germany",
    "certificate": "yes"
  },
  {
    "mark": "TOYOTA",
    "price": "48 000",
    "color": "blue",
    "constructor": "Jon Hubert",
    "door": "3",
    "max_people": "7",
    "country": "Japan",
    "certificate": "yes"
  },
  {
    "mark": "Volkswagen",
    "price": "36 000",
    "color": "red",
    "constructor": "Pier Sun",
    "country": "Germany",
    "certificate": "no"
  },
];

function car(arr, mark) {
  let carss = arr.filter(function(item) {
    return item.mark === mark;
  })
  return carss !== mark ? carss[0] : "car sold";
};

console.log(car(arr, "Mercedes-benz", ));

1 个答案:

答案 0 :(得分:1)

有两个问题:

  1. 您不能使用!==(或!======)比较数组。即使它们具有相同的内容,两个不同的数组也永远不会彼此相等。

  2. filter不是在数组中搜索匹配项的正确选择。在这种情况下,由于您要退回找到的第一辆汽车,因此可以使用find(具有与现在相同的谓词功能)。

使用find

function car(arr,mark ){
  let car = arr.find(function(item){
     return item.mark === mark ;
  })
  return car || "car sold";
}

或者您可以使用箭头功能

function car(arr,mark ){
  let car = arr.find(item => item.mark === mark);
  return car || "car sold";
}

实时示例:

const arr = [
   {  
     "mark":"BMW",
     "price":"55 000",
     "color":"red",
     "constructor":"Billy%Zekun",
     "country":"Germany",
     "certificate":"yes"
  },
  {  
    "mark":"Mercedes-benz",
    "price":"63 000", 
    "color":"blue",
    "constructor":"Jon%Adams",
    "country":"Germany",
    "certificate":"yes"
  },
  {  
    "mark":"TOYOTA", 
    "price":"48 000", 
    "color":"blue",
    "constructor":"Jon Hubert",
    "door":"3"  ,
    "max_people":"7",
    "country":"Japan",
    "certificate":"yes"
  },
  {  
    "mark":"Volkswagen",
    "price":"36 000", 
    "color":"red",
    "constructor":"Pier Sun",
    "country":"Germany",
    "certificate":"no"
  },
 ];

function car(arr,mark ){
  let car = arr.find(item => item.mark === mark);
  return car || "car sold";
}

console.log(car(arr , "Mercedes-benz"));

(您在,调用中还有一个额外的console.log,我在示例中将其删除。之所以有效,是因为现代JavaScript中的参数列表中允许使用尾部逗号,但只有少数失败年前。)