简体   繁体   中英

forEach is returning undefined

I want my foreach() to loop through an array of maps and check if the type value matches. If not return the else statement.

Function

function checkCars(carData) {
        const cars = carData.models;

        models.forEach(model => {
            if (model.type === 'Toyota' || model.type === 'Hyundai') {
                return "Type A";
            } else {
                return "Type B";
            }
        });
    }

Database

"models": [
  {type: "Toyota"}
  {type: "Hyundai"}
  {type: "Audi"}
  {type: "VW"}
]

The return value of Array.prototype.forEach() is undefined , you can not return anything explicitly from forEach() .

You can try with Array.prototype.map() instead:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

function checkCars(carData) {
  const cars = carData.models;

  return models.map(model => {
    if (model.type === 'Toyota' || model.type === 'Hyundai') {
      return "Type A";
    } else {
      return "Type B";
    }
  });
}

forEach has no return value. You should use map function to change the element's types.

If you want to transform the array, you want map :

function checkCars(carData) {
  const cars = carData.models;

  return models.map(model => {
    if (model.type === 'Toyota' || model.type === 'Hyundai') {
      return "Type A";
    } else {
      return "Type B";
    }
  });
}

You can use something like this:

function checkCars(carData) {
        const cars = carData.models;
        let type = "Type A"
        models.forEach(model => {
            if (model.type !== 'Toyota' && model.type !== 'Hyundai') {
                type = "Type B";
            }
        });
        return type
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM