简体   繁体   English

Javascript数组中省略了元素 - 问题

[英]Elements are getting omitted from Javascript array - problem

I want to sort an array from lowest number to highest.我想将数组从最低数字排序到最高数字。 But when I execute the following code, some of my array elements get missed!但是当我执行以下代码时,我的一些数组元素会丢失! I don't know why.我不知道为什么。 I need help.`// Sort an array from lowest to highest我需要帮助。`// 将数组从最低到最高排序

 function findSmallest(numArr) { let smallestNumber = numArr[0] for (let i = 0; i < numArr.length; i++) { if (numArr[i + 1] < smallestNumber) { smallestNumber = numArr[i + 1] } } return smallestNumber; } function getSortedArray(arr) { let sortedArray = [] for (j = 0; j < arr.length; j++) { let smallest = findSmallest(arr) let smallestNumbmerIndex; for (let i = 0; i < arr.length; i++) { if (arr[i] === smallest) { smallestNumbmerIndex = i } } arr.splice(smallestNumbmerIndex, 1) sortedArray.push(smallest) } return sortedArray } let myArr = [23, 2, 12, 4] console.log(getSortedArray(myArr)) // console output => [2, 4] , the rest elements get omitted

since arr shrinks in each iteration, your for loop won't run 4 iterations, only 2 -由于arr在每次迭代中都会缩小,因此您的 for 循环不会运行 4 次迭代,只有 2 次 -

use while(arr.length){ instead of the for j loop使用while(arr.length){而不是for j循环

 function findSmallest(numArr) { let smallestNumber = numArr[0] for (let i = 0; i < numArr.length; i++) { if (numArr[i + 1] < smallestNumber) { smallestNumber = numArr[i + 1] } } return smallestNumber; } function getSortedArray(arr) { let sortedArray = [] while(arr.length) { let smallest = findSmallest(arr) let smallestNumbmerIndex; for (let i = 0; i < arr.length; i++) { if (arr[i] === smallest) { smallestNumbmerIndex = i } } arr.splice(smallestNumbmerIndex, 1) sortedArray.push(smallest) } return sortedArray } let myArr = [23, 2, 12, 4] console.log(getSortedArray(myArr)) // console output => [2, 4] , the rest elements get omitted

We can use a while loop, or we can store the length of array into a variable before the for loop, so that it will not change:我们可以使用while循环,或者我们可以在for循环之前将数组的长度存储到一个变量中,这样它就不会改变:

 function findSmallest(numArr) { let smallestNumber = numArr[0] for (let i = 0; i < numArr.length; i++) { if (numArr[i + 1] < smallestNumber) { smallestNumber = numArr[i + 1] } } return smallestNumber; } function getSortedArray(arr) { let sortedArray = [] // we can store the array length into a variable let length = arr.length for (j = 0; j < length; j++) { let smallest = findSmallest(arr) let smallestNumbmerIndex; for (let i = 0; i < arr.length; i++) { if (arr[i] === smallest) { smallestNumbmerIndex = i } } arr.splice(smallestNumbmerIndex, 1) sortedArray.push(smallest) } return sortedArray } let myArr = [23, 2, 12, 4] console.log(getSortedArray(myArr))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM