javascript - 使用整数数组参数的排序函数不起作用
问题描述
我是一个尝试学习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");
}
解决方案
据我了解。错误就在这里
原始代码:
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;
}
推荐阅读
- sql - ORACLE SQL 重写查询
- python - python会接受-(破折号)作为`open()`的文件名以写入标准输出吗?
- javascript - Angular/Node 验证用户
- c# - LineRenderer 对齐不面向 Vuforia ARCamera
- swift - 修改结构模型时将数据传回控制器
- python - 试图通过在打印语句中使用标识运算符来获取布尔值。但它给了我错误的价值观如何解决?
- python-3.x - Python Boto3 - 在一个放置请求中将图像上传到 S3
- javascript - ASP.NET 验证器,在 JavaScript 中验证
- c++ - 在 C++ 中分配 3D 数组最惯用的方法是什么?
- c# - 如何在多线程环境中正确使用 EasyNetQ