首页 > 解决方案 > 使用整数数组参数的排序函数不起作用

问题描述

我是一个尝试学习JS的初学者,我有一些基础知识。我写了一个函数来实现对给定数组的插入排序(数组作为参数传递给函数)。

当我初始化数组并为其赋值时,例如 sampleArray = [1,35,73,234,1,1,356]; 并将其传递给我的函数,它完美地工作。但是,如果我尝试传递由用户输入填充的数组 - 或从两个给定数组合并的数组(我的原始作业),它不起作用 - 没有异常或错误,它只是......没有t 按预期排序。

一直在纠结这个问题,不知道去哪里找?

function sortArray(arrT) {
    for (let i = 1; i < arrT.length; i++){
        var tempMax = arrT[i];
        var j = i - 1;
        while ((j >= 0) && (arrT[j] > tempMax)) {
            console.log(arr1 + "\nj=" + j + " i=" + i);
            arrT[j+1] = arrT[j];
            j--;
        }
        arrT[j+1] = tempMax;
    }
    console.log("sorted array is (inside loop) :\n" +arrT);
    return arrT;
}

对于由提示的 while 循环填充的数组,例如它等于上面的示例数组,结果是 1,1,1,234,35,356,73

作为参考,虽然它远非优雅,但我正在使用它来填充数组:

for (let i = 0, x = ""; x !== "x"; i++) {
    x = prompt("press x to finish, enter to continue");
    if (x == "x") { break }
    arr1[i]=prompt("enter");
} 

标签: javascriptarraysfunctionsorting

解决方案


据我了解。错误就在这里

原始代码:

for (let i = 0, x = ""; x !== "x"; i++) {
    x = prompt("press x to finish, enter to continue"); 
    if (x == "x") { break }
    arr1[i]=prompt("enter");//do not use prompts while unnecessary. Just replace it with x;
} 

更正一:

for (let i = 0, x = ""; x !== "x"; i++) {
    x = prompt("press x to finish, enter to continue"); 
    if (x == "x") { break }
    /*
    you can also improve your code by applying few checks
    if(!isNaN(x)) continue; // --- to skip when input value isn't a number
    */

    arr1[i]=x;
} 

推荐阅读