简体   繁体   中英

Test run on freecodecamp is failing even though code runs successfully from Chrome developer console?

最大数字 I'm under basic algorithm section of freecodecamp and have to write a function to return the largest numbers in sub-arrays. Code runs perfectly in Chrome developer console, but all test runs are failing:

function largestOfFour(arr) {
  new_arr = [];[![enter image description here][1]][1]
  for(var i = 0; i < arr.length; i++){
    var highestNum = Math.max.apply(null, arr[i]);
    new_arr.push(highestNum);
  };
  return new_arr;
}; 

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Here are the 4 tests that are failing. Also took a screenshot:

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return an array.
largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27, 5, 39, 1001].
largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) should return [9, 35, 97, 1000000].
largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]) should return [25, 48, 21, -3].

You should show the actual error from their output preview.

Try var new_arr = [];

This returns just fine

function largestOfFour(arr) {
  new_arr = [];
  for(var i = 0; i < arr.length; i++){
    var highestNum = Math.max.apply(null, arr[i]);
    new_arr.push(highestNum);
  };
  return new_arr;
}; 

let arr = [[4000, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]
largestOfFour(arr) // [4000, 27, 39, 1001]

The test are most likely failing because the array should not be returned, but rather printed to the console. Change return to console.log :

console.log(new_arr);

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