JavaScript中数组sort方法未返回预期结果的原因探究——是否与数组为对象类型相关?
Array.sort() Return the Expected Numeric Order in JavaScript? Great question! Let’s break down why you’re seeing that unexpected sort result—it has nothing to do with arrays being objects in JavaScript, and everything to do with how the default Array.sort() method works.
The Root Cause: Default sort() Behavior
By default, JavaScript’s Array.sort() converts all elements to strings and compares them based on their Unicode code point values, not their numeric magnitude.
Let’s walk through your specific example step by step:
- After squaring and filtering out 0s and 1s, your
arrayWithoutZerosis[16, 9, 100](from the originalnumsvalues-4,3,10). - When you call
sort()without a custom comparator, these numbers get converted to strings:"16","9","100". - String comparison happens character by character:
"100"vs"16": The first character is"1"for both, but the second character"0"(Unicode code 48) is smaller than"6"(code 54), so"100"comes before"16"."16"vs"9": The first character"1"(code 49) is smaller than"9"(code 57), so"16"comes before"9".
- The end result of the default sort is
[100, 16, 9], which explains why your final array becomes[0, 1, 100, 16, 9].
Why Arrays Being Objects Isn’t the Issue
Yes, arrays are reference types in JavaScript, but that doesn’t affect how sort() operates. The problem is purely the default sorting logic, not the type of the array itself.
The Fix: Use a Numeric Comparator Function
To sort numbers by their actual numeric value, you need to pass a comparator function to sort(). For ascending order, use:
let finalArray = arrayWithoutZeros.sort((a, b) => a - b);
This function works because:
- If
a < b,a - breturns a negative number, soais placed beforeb. - If
a > b,a - breturns a positive number, sobis placed beforea. - If
a === b, it returns 0, leaving their positions unchanged.
For descending order, reverse the logic: (a, b) => b - a.
A Quick Note on Your First Code Snippet
Your first example worked by accident—using sort().reverse() gave you the correct ascending order for your specific set of numbers, but this isn’t reliable for all numeric arrays. For example, if your arrayWithoutZeros was [10, 2, 30], the default sort() would give [10, 2, 30], and reversing that would give [30, 2, 10]—which is definitely not ascending. Always use the comparator function for numeric sorting to avoid edge cases.
内容的提问来源于stack exchange,提问作者Sanjay Kapilesh

