在函数中使用.sort对数组进行排序等于在JavaScript中未定义



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

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)

1(您必须从函数sortSpeciesByTeethreturn,默认情况下会返回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; }

在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))

您最初的sortSpeciesByTeethes函数实际上是对列表进行排序,但它只是从末尾掉下来,没有返回任何内容,因此隐式地将undefined返回到console.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)