第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

了解代碼在幕后究竟做了什么

了解代碼在幕后究竟做了什么

嗶嗶one 2021-12-12 09:52:54
我不知道這個問題是否真的被問到,但我有一個帶有 for 循環(huán)的運行代碼,它對數(shù)字數(shù)組進行排序。但我不明白代碼背后的想法。如果有經(jīng)驗的人能告訴我幕后發(fā)生的事情,那就太好了。這是代碼: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);
查看完整描述

1 回答

?
慕神8447489

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);


查看完整回答
反對 回復(fù) 2021-12-12
  • 1 回答
  • 0 關(guān)注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號