the reason for writing this article
My current projects rarely use algorithms, so things in this area are naturally a bit rusty. The most recent code encountered the need to get the maximum value from the array, at that time I did not consciously think of the JS sort () function, now want to really some "sin", at that time, I still feel a little smug: "Well, I use the JS built-in method to solve a usually need to use sorting algorithm to solve the problem, Code short, not to write headache traversal and comparison, readability is ok ... ”。 The inner play is heavy, isn't it? Cough, ah, I am still tender and lazy. JS Endogenous sort function is also used in the sorting, see Segmentfault on the JS endogenous sort () function is how to achieve.
Artifice
JS has a lot of "artifice", sometimes I will often deliberately to use these "artifice" (note that I am not against the use of it, but sometimes it is not necessary to use). For example, the maximum value in the array, JS in the array does not have the original method to find the maximum value, but math has:
Math.max (22, 79, 33)//79
If you want to use an array, you can use it:
var arr = [22, 79, 33]; Math.max.apply (null, arr); 79
Or do not use the Apply method, you convert the array into a string, using the eval () method to perform stitching as "Math.max (NUM1, num2, num3)" JS code is also possible:
var max = eval ("Math.max (" + arr.join (', ') + ")"); 79
If you don't think about it, you can use the sort () function I mentioned above as well:
var arr = [22, 79, 33]; var Getmax = function (arr) { var Copyarr = Json.parse (arr)); var len = copyarr.length; Copyarr.sort (); return copyarr[len-1]; }; Getmax (arr); 79
Stupid method
See now, you must marvel at the power of JS, but sometimes too dependent on its "artifice" will let oneself in a "arrogant" state, after all, the power of JS does not mean that your own coding level is strong. So go back to the basics and use your stupid methods to exercise your brain power:
var arr = [+, +]; var Getmax = function (arr) { var len = arr.length, max = arr[0]; while (len--) { if (max >= Arr[len]) { continue; } max = Arr[len]; } return Max; }; Getmax (arr); 79