找出多个数组中的最大数
解法一:loop
function largestOf(arr) {
constant result=[];
for(let i = 0 ; i < arr.length; i++){
let largestNumber=arr[i][0];
for( let j = 0; j < arr[i].length; j++){
if(arr[i][j] > largestNumber){
largestNumber=arr[i][j];
}
}
result[i]=largestNumber;
}
return result;
}
解法二:用reduce,map,三目运算符
function largestOf (arr){
return arr.map(function(group){
return group.reduce(function(pre,cur){
return pre>cur?pre:cur;
});
});
}
解法三:
function largestOfFour(arr) {
return arr.map(Function.apply.bind(Math.max,null));
}
apply 用于传入数组作为参数,第一个参数为null,map需要回调函数,所以用bind创造一个函数,调用时传入this参数
TL;DR: We build a special callback function (using the
Function.bind
method), that works just likeMath.max
but also hasFunction.prototype.apply
's ability to take arrays as its arguments.
- We start by mapping through the elements inside the main array. Meaning each one of the inner arrays.
- Now the need a callback function to find the max of each inner array provided by the map.
So we want to create a function that does the work of
Math.max
and accepts input as an array (which by it doesn’t by default).In other words, it would be really nice and simple if this worked by itself:
Math.max([9, 43, 20, 6]); // Resulting in 43
Alas, it doesn’t.
- To do the work of accepting arguments in the shape of an array, there is this
Function.prototype.apply
method, but it complicates things a bit by invoking the context function.i.e.
Math.max.apply(null, [9, 43, 20, 6]);
would invoke something like aMax.max
method. What we’re looking for… almost.Here we’re passing
null
as the context of theFunction.prototype.apply
method asMath.max
doesn’t need any context.
- Since
arr.map
expects a callback function, not just an expression, we create a function out of the previous expression by using theFunction.bind
method.- Since,
Function.prototype.apply
is a static method of the sameFunction
object, we can callFunction.prototype.bind
onFunction.prototype.apply
i.e.Function.prototype.apply.bind
.- Now we pass the context for the
Function.prototype.apply.bind
call (in this case we wantMath.max
so we can gain its functionality).- Since the embedded
Function.prototype.apply
method will also require a context as it’s 1st argument, we need to pass it a bogus context.
So, we pass
null
as the 2nd param toFunction.prototype.apply.bind
which gives a context to theMath.max
method.Since,
Math.max
is independent of any context, hence, it ignores the bogus context given byFunction.prototype.apply
method call.Thus, our
Function.prototype.apply.bind(Math.max, null)
makes a new function accepting thearr.map
values i.e. the inner arrays.
解法四:递归 recursive
function largestOfFour(arr, finalArr = []) {
return !arr.length
? finalArr
: largestOfFour(arr.slice(1), finalArr.concat(Math.max(...arr[0])))
}
freeCodeCamp Challenge Guide: Return Largest Numbers in Arrays - Guide - The freeCodeCamp Forum