JavaScript调用Array.sort()后数组未改变?自定义排序回调问题求助
解决Array.sort()不生效的问题
你的代码里有两个关键错误导致sort方法没起作用:
- 多return语句导致逻辑无效:第一个
return a < b ? 0 : 1;执行后,后面的所有return代码都不会被触发,相当于你始终在按这一条错误逻辑返回值,后面的测试代码根本没生效。 - sort回调的返回值逻辑错误:Array.sort()要求回调返回负数、0、正数,分别对应
a应该排在b前面、两者位置不变、a应该排在b后面。你原来只返回0或1,当a的索引小于b时返回0(位置不变),否则返回1(a放b后面),这种逻辑无法驱动数组完成正确排序。
修正后的代码如下:
const days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]; const toSort = ["monday", "tuesday", "thursday", "friday", "wednesday"]; toSort.sort((a, b) => { const indexA = days.indexOf(a); const indexB = days.indexOf(b); // 返回索引差值,让sort根据正负自动调整元素顺序 return indexA - indexB; }); console.log(toSort); // 输出:["monday", "tuesday", "wednesday", "thursday", "friday"]
如果想用三元表达式实现相同逻辑,也可以写成:
return indexA < indexB ? -1 : indexA > indexB ? 1 : 0;
内容的提问来源于stack exchange,提问作者Hello World
相关产品推荐
相关产品推荐

