简体   繁体   中英

Javascript - Why isn't my call back working? I'm getting an empty array instead of array of even numbers

I'm trying to filter the array using callbacks, where it returns only even numbers, But im getting [] empty array as output, I defnitely wanna make use of isEvenOrOdd

enter code here
//Defining an array
let numbers = [1,2,3,4,5,6,7,8,9];

//Define callback function isEvenOrOdd; Making use of this function is mandatory
function isEvenOrOdd(x){
  // let x;
  (x) => (x % 2 === 0)
  console.log(x % 2);
}

//Call callback function in main function filter
function filterNumbers(array, callback){
  return array.filter(callback);
  // console.log(callback)
}

//Displays only even numbers
filterNumbers(numbers, isEvenOrOdd);
let numbers = [1,2,3,4,5,6,7,8,9];

function isEvenOrOdd(x){
   console.log(x % 2);
  return (x % 2) === 0
 
}

function filterNumbers(array, callback){
  return array.filter(callback);
}

filterNumbers(numbers, isEvenOrOdd);

I have fix your code. You must read this link before see result code.

A notice:

  • Array filter is return a array as result.
  • Array filter need a boolean return inside callback function. TRUE is keep value, and FALSE is remove value.

** Your wrong is written the console.log in wrong place, and don't understand clearly what array filter need and do.

//Defining an array
let numbers = [1,2,3,4,5,6,7,8,9];

//Define callback function isEvenOrOdd; Making use of this function is mandatory
function isEvenOrOdd(x){
  // let x;
  return x % 2 === 0;
}

//Call callback function in main function filter
function filterNumbers(array, callback){
  return array.filter(callback);
  // console.log(callback)
}

//Displays only even numbers
var r = filterNumbers(numbers, isEvenOrOdd);
console.log(r);

You must return true/false from the isEvenOrOdd function in order to get the result

 let numbers = [1,2,3,4,5,6,7,8,9]; function isEvenOrOdd(x){ return (x % 2 === 0) } //Call callback function in main function filter function filterNumbers(array, callback){ return array.filter(callback); } //Displays only even numbers const result = filterNumbers(numbers, isEvenOrOdd); console.log(result)

let numbers = [1,2,3,4,5,6,7,8,9];
let evenNumbers = [];

function isEvenOrOdd(x){
  return x % 2 == 0;
}

function filterNumbers(array, callback){
  return array.filter(callback);
}

evenNumbers = filterNumbers(numbers, isEvenOrOdd);

console.log(evenNumbers);

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