繁体   English   中英

在函数中使用 .sort 对数组进行排序等于 JavaScript 中的 Undefined

[英]Sorting an Array using .sort in an function equals Undefined in JavaScript

我想创建一个新数组,它是我数组的副本,同时使用存储在 numTeeth 中的值对其进行排序。 我正在使用函数 sort 来完成这个任务。 问题是,如果我尝试使用控制台日志调试它,它会显示未定义的值。

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

const sortSpeciesByTeeth = arrayIn => {
  arrayIn.sort( function (a, b) {
    return a.numTeeth - b.numTeeth;
  });
}

console.log(sortSpeciesByTeeth(speciesArray))

如果我使用相同的代码而不将其声明为单独的函数,尽管它对原始数组进行了排序,它仍然可以工作。 我在最终代码中不想要的。 例子

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

speciesArray.sort( function (a, b) {
  return a.numTeeth - b.numTeeth;
});

console.log(speciesArray)

在 JS 箭头函数中,只有当函数体没有用大括号包裹时,才会隐式返回第一条语句。 这意味着sortSpeciesByTeeth不返回任何内容。 您只需要添加一个return语句:

 const speciesArray = [ {speciesName:'shark', numTeeth:50}, {speciesName:'dog', numTeeth:42}, {speciesName:'alligator', numTeeth:80}, {speciesName:'human', numTeeth:32} ]; const sortSpeciesByTeeth = arrayIn => { return arrayIn.sort(function (a, b) { return a.numTeeth - b.numTeeth; }); } console.log(sortSpeciesByTeeth(speciesArray))

您原来的 sortSpeciesByTeeth 函数实际上是对列表进行排序,但它只是从末尾掉下来而没有返回任何内容,因此隐式返回undefinedconsole.log语句。 (因此,如果您在记录之前对数组进行排序,您也将获得所需的结果):

 const speciesArray = [ {speciesName:'shark', numTeeth:50}, {speciesName:'dog', numTeeth:42}, {speciesName:'alligator', numTeeth:80}, {speciesName:'human', numTeeth:32} ]; const sortSpeciesByTeeth = arrayIn => { arrayIn.sort(function (a, b) { return a.numTeeth - b.numTeeth; }); } sortSpeciesByTeeth(speciesArray) console.log(speciesArray)

1)你必须从函数sortSpeciesByTeeth return一些东西,默认情况下返回undefind

2)如果您想要原始数组的副本,则可以使用扩展语法

sort() 方法就地对数组的元素进行排序并返回排序后的数组。 - MDN

const sortSpeciesByTeeth = (arrayIn) => {
  return [...arrayIn.sort((a, b) => a.numTeeth - b.numTeeth)];
};

或者

const sortSpeciesByTeeth = (arrayIn) => [
  ...arrayIn.sort(({ numTeeth: nT1 }, { numTeeth: nT2 }) => nT1 - nT2),
];

 const speciesArray = [ { speciesName: "shark", numTeeth: 50 }, { speciesName: "dog", numTeeth: 42 }, { speciesName: "alligator", numTeeth: 80 }, { speciesName: "human", numTeeth: 32 }, ]; const sortSpeciesByTeeth = (arrayIn) => { return [ ...arrayIn.sort(function (a, b) { return a.numTeeth - b.numTeeth; }), ]; }; console.log(sortSpeciesByTeeth(speciesArray));
 /* This is not a part of answer. It is just to give the output full height. So IGNORE IT */ .as-console-wrapper { max-height: 100% !important; top: 0; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM