简体   繁体   English

JavaScript for loop停止在中间运行

[英]JavaScript for loop stops running in the middle

I'm trying to return an array of numbers in descending order (biggest in the front). 我正在尝试以降序返回数字数组(前面最大)。

My function seems to work but just quits in the middle. 我的功能似乎可以正常工作,但仅在中间退出。

 let array = [1, 9, 8, 7, 2, 6, 3, 5]; let sorted = []; function sortNumbers(array) { for (var i = 0; i < array.length; i++) { let max = array.reduce(function(a, b) { console.log(`a: ${a} b: ${b}`); return Math.max(a, b); }); let maxIdx = array.indexOf(max); let biggest = array.splice(maxIdx, 1); sorted.push(biggest); } console.log('sorted array is: ', sorted.join('')); //returns 9876 } sortNumbers(array); 

The problem you are having is being caused by splicing inside the loop. 您遇到的问题是由循环内的splicing引起的。 You change the array as you're looping through it. 在遍历数组时可以更改它。 The quick fix is to loop through the array backwards so you set the correct length at the beginning of the loop: 快速解决方案是向后遍历数组,因此您可以在循环开始时设置正确的长度:

for (var i = array.length; i > 0; i--) {
  // etc
}

 let array = [1, 9, 8, 7, 2, 6, 3, 5]; let sorted = []; function sortNumbers(array) { for (var i = array.length; i > 0; i--) { let max = array.reduce(function(a, b) { console.log(`a: ${a} b: ${b}`); return Math.max(a, b); }); let maxIdx = array.indexOf(max); let biggest = array.splice(maxIdx, 1); sorted.push(biggest); } console.log('sorted array is: ', sorted.join('')); //returns 9876 } sortNumbers(array); 

As mentioned by others, it's generally risky to splice the array while looping over it. 正如其他人所提到的,在循环遍历数组时通常会有风险。 Looping backwards can help avoid issues where elements are removed and the index is thrown off, skipping elements, causing logic errors or throwing out of bounds exceptions. 向后循环可以帮助避免出现以下问题:删除元素并抛出索引,从而跳过元素,从而导致逻辑错误或抛出异常。

Having said that, it seems you're attempting selection sort; 话虽如此,看来您正在尝试选择排序; however, if you're just trying to sort the array in reverse and join, your approach can be simplified to: 但是,如果您只是想对数组进行反向排序和合并,则方法可以简化为:

 const array = [1, 9, 8, 7, 2, 6, 3, 5]; const sorted = array.sort((a, b) => b - a); console.log(sorted.join("")); 

Is there a reason you're doing this yourself? 您有理由自己这样做吗?

console.log(array.sort(function(a, b) { return a<b ? 1 : a>b ? -1 : 0; } ))



console.log(array.sort().reverse())

use Underscore.Js for doing various manipulations on Arrays and Objects. 使用Underscore.Js对数组和对象进行各种操作。

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects Underscore是一个JavaScript库,提供了许多有用的功能编程助手,而无需扩展任何内置对象

go to following the link: https://underscorejs.org/# 请转到以下链接: https : //underscorejs.org/#

_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); }); _.sortBy([1,2,3,4,5,6],function(num){return Math.sin(num);});

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

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