You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript封装.sort()数组排序函数返回Undefined问题求解

问题解决

根因分析

  • 函数返回值缺失:你定义的sortSpeciesByTeeth没有编写return语句,JavaScript 函数无显式返回时默认返回undefined,这是打印结果为空的直接原因。
  • 原数组被修改:Array.sort()是原地排序方法,会直接修改调用它的数组本身,不符合你保留原数组的需求。

正确实现代码

const speciesArray = [ 
  {speciesName:'shark', numTeeth:50}, 
  {speciesName:'dog', numTeeth:42}, 
  {speciesName:'alligator', numTeeth:80}, 
  {speciesName:'human', numTeeth:32}
];

const sortSpeciesByTeeth = arrayIn => {
  // 浅拷贝原数组生成新数组,避免修改原数组
  const sortedArray = [...arrayIn];
  // 对新数组排序并返回
  return sortedArray.sort((a, b) => a.numTeeth - b.numTeeth);
}

console.log(sortSpeciesByTeeth(speciesArray));
// 可自行打印原数组验证未被修改
console.log(speciesArray);

兼容写法

如果运行环境不支持ES6扩展运算符,可以用slice()方法实现数组浅拷贝:

const sortedArray = arrayIn.slice();

内容的提问来源于stack exchange,提问作者HTF Games Studio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:45:03