简体   繁体   中英

How to convert it into es6 arrow functions? in Vanilla JS

Hi i want to convert this code to es6 arrow functions here is the sample code. but i'm getting an error like this:

在此处输入图片说明

 let pets = [ {name: "Meowsalot", species: 'cat', age: 2}, {name: "Barksalot", species: 'dog', age: 4}, {name: "Purrsloud", species: 'cat', age: 10} ] pets.push({ name: 'Puppster', species: 'dog', age: 1 }) let ourTest = pets.map(nameOnly) function nameOnly(x) { return x.name } let dogs = pets.filter(onlyDogs) function onlyDogs(x) { return x.species == 'dog' } function onlyBabies(x) { return x.age < 3 } let babyDogNames = pets.filter(onlyDogs).filter(onlyBabies).map(nameOnly) // here is my es6 version let ourTest = pets.map(nameOnly => nameOnly.name); let dogs = pets.filter(onlyDogs => onlyDogs.species == "dog"); (onlyBabies) => onlyBabies.age < 3 let babyDogNames = pets.filter(onlyDogs).filter(onlyBabies).map(nameOnly); console.log(babyDogNames);

You are passing a not declared arrow function in the line let babyDogNames = pets.filter(onlyDogs).filter(onlyBabies).map(nameOnly); . You should pass either anonymous arrow functions

let babyDogNames = pets.filter(pet => pet.species == 'dog') // filter only dogs
    .filter(pet => pet.age < 3)          // filter only babies
    .map(pet => pet.name);               // get names

or declare all arrow functions as variables and then pass them:

const onlyDogs = pet => pet.species == 'dog';
const onlyBabies = pet => pet.age < 3;
const onlyNames = pet => pet.name;

let babyDogNames = pets.filter(onlyDogs).filter(onlyBabies).map(onlyNames);

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