问题
The result that's logged to the console (answer) is the correct one, but it's coming out of the function as undefined. What is going on?
let sorted = [];
function reset(){
sorted = [];
}
function sort(list) {
let least = list[0];
for (let i = 0; i < list.length; i++){
if (list[i] < least ){
least = list[i];
}
}
sorted.push(least);
list.splice(list.indexOf(least),1);
if (list[0] !== undefined){
sort(list)
}
else {
let answer = sorted;
reset();
console.log(answer);
return answer;
}
}
let sampleArray = [3,2,1];
sort(sampleArray);
回答1:
In the if
branch you correctly call sort
recursively, but just ignore the returned value instead of returning it. Just return it and you should be fine:
if (list[0] !== undefined) {
return sort(list); // Here
}
else {
// Rest of your code...
回答2:
@Mureinik is correct about the problem. However, more to the point, if you want to make a sorted copy of the array in increasing order, you can easily do so using .slice() and .sort():
let sampleArray = [3, 1, 2];
// sorted array
let sortedArray = sampleArray.slice().sort((a, b) => a - b);
console.log(sortedArray);
// original array preserved
console.log(sampleArray);
(I'm getting a 500 error so here's an alternative demo for now)
来源:https://stackoverflow.com/questions/49882255/why-is-this-sorting-function-returning-undefined