1 回答
TA貢獻1780條經(jīng)驗 獲得超1個贊
首先,讓你的代碼正確縮進而不利用可選語法(大括號和分號)將大大有助于你理解代碼的處理方式。技術(shù)上,大括號不需要與for和if語句,如果只有一個聲明,內(nèi)環(huán)路或的分支內(nèi)執(zhí)行if。此外,從技術(shù)上講,JavaScript 不要求您在語句的末尾放置分號。不要利用這些可選語法中的任何一種,因為它只會使事情變得更加混亂并可能導(dǎo)致代碼中的錯誤。
考慮到這一點,您的代碼確實應(yīng)該如下編寫。這段代碼的工作是對數(shù)組中的項目進行排序。它通過遍歷數(shù)組并始終檢查當(dāng)前數(shù)組項和它之前的項來完成此操作。如果項目無序,則交換值。
請參閱注釋以了解每行的作用:
// Declare and populate an array of numbers
var 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);
添加回答
舉報
