quiz:
const numbers = [33, 2, 8];
numbers.sort(); //[2, 33, 8]
Solution:
JavaScript is a dynamically typed language, which means that all standard library functionality must, at some point, decide how to work for most, if not all, use-cases.
Always keep in mind that the following array is valid:
const array = ["1", true, 55, 1.421, "foo", {}];
Array.prototype.sort
now needs to make a decision on how to handle such scenarios, and the solution is pretty straight-forward:
Convert all values to their string representation (because every value in JavaScript can always be converted to a string!), and then sort them in lexicographic order(字典順序).
Which basically makes sort see the array as this:
const intermediate = ["33", "2", "8"];
And in lexicographic order, no matter how many characters a string has, comparison starts at position 0, and "3"
comes before "8"
.
And in the end, the result is this:
["2", "33", "8"];
沒有留言:
張貼留言