我不知道这个问题是否真的被问到,但我有一个带有 for 循环的运行代码,它对数字数组进行排序。但我不明白代码背后的想法。如果有经验的人能告诉我幕后发生的事情,那就太好了。这是代码:
var a = [1, 7, 2, 8, 3, 4, 5, 0, 9];
for(i=1; i<a.length; i++)
for(k=0; k<i; k++)
if(a[i]<a[k]){
var y = a[i]
a[i]= a[k]
a[k]=y;
}
alert(a);
哔哔one
浏览 119回答 1
1回答
慕神8447489
首先,让你的代码正确缩进而不利用可选语法(大括号和分号)将大大有助于你理解代码的处理方式。技术上,大括号不需要与for和if语句,如果只有一个声明,内环路或的分支内执行if。此外,从技术上讲,JavaScript 不要求您在语句的末尾放置分号。不要利用这些可选语法中的任何一种,因为它只会使事情变得更加混乱并可能导致代码中的错误。考虑到这一点,您的代码确实应该如下编写。这段代码的工作是对数组中的项目进行排序。它通过遍历数组并始终检查当前数组项和它之前的项来完成此操作。如果项目无序,则交换值。请参阅注释以了解每行的作用:// Declare and populate an array of numbersvar a = [1, 7, 2, 8, 3, 4, 5, 0, 9];// Loop the same amount of times as there are elements in the array// Although this code will loop the right amount of times, generally// loop counters will start at 0 and go as long as the loop counter// is less than the array.length because array indexes start from 0.for(i=1; i<a.length; i++){ // Set up a nested loop that will go as long as the nested counter // is less than the main loop counter. This nested loop counter // will always be one less than the main loop counter for(k=0; k<i; k++){ // Check the array item being iterated to see if it is less than // the array element that is just prior to it if(a[i]<a[k]){ // ********* The following 3 lines cause the array item being iterated // and the item that precedes it to swap values // Create a temporary variable that stores the array item that // the main loop is currently iterating var y = a[i]; // Make the current array item take on the value of the one that precedes it a[i]= a[k]; // Make the array item that precedes the one being iterated have the value // of the temporary variable. a[k]=y; } }} alert(a);