为什么此排序函数返回未定义? [英] Why is this sorting function returning undefined?

查看:122
本文介绍了为什么此排序函数返回未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

记录到控制台( answer )的结果是正确的结果,但它是未定义的功能.发生了什么事?

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

推荐答案

if分支中,您可以正确地递归调用sort,但只是忽略返回的值而不是返回它.只需将其退还,就可以了:

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...

这篇关于为什么此排序函数返回未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆