iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 10
1
自我挑戰組

Head First!從頭開始學JS 《深入淺出 JavaScript 程式設計》讀書筆記系列 第 10

Day10. 迴圈和函式摻在一起做成撒尿牛丸

本日閱讀進度:第四章 陣列(146~166頁)

重點摘要:

  1. 事後遞增運算符 VS 事後遞減運算符
    JavaScript裡難得有比Ruby簡潔的寫法,以下是兩個例子。
  • 事後遞增運算符
x = x + 1
可以改寫為
x++
  • 事後遞減運算符
x = x - 1
可以改寫為
x--
  1. 稀疏陣列
    稀疏陣列是一個包含空隙的陣列,例如索引0和索引2有值,但是索引1沒有值,此時索引1為undefined(未定義)。即使它沒有值,也會佔用電腦的記憶體,故不建議建立這樣的陣列。

  2. while迴圈 VS for迴圈
    當不知道要循環幾次時,通常會使用while迴圈,while迴圈會循環到條件不相符為止。當知道迴圈要執行幾次時,通常會使用for迴圈。

  3. 將新值加入陣列
    可以使用push來將一個新值加入陣列。

var emptyBox = [];
  emptyBox.push("x", true, 5);
console.log(emptyBox);
// ["x", true, 5]

本章的後半段結合了for迴圈和函式來判斷陣列裡CP值最高(得分最高、成本最低)的產品,原本的陣列裡有36個值,來寫個6個值的精簡版吧。(但迴圈和函式的code還是很不精簡XD)

var scores = [60, 50, 60, 58, 54, 52];
var highScore = 0;
for (var i = 0; i < scores.length; i++) {
  output = "編號" + i + "得" + scores[i] + "分";
  console.log(output);
  //"編號0得60分" 
  //"編號1得50分"
  //以下略
  
  if (scores[i] > highScore) {
    highScore = scores[i];
  }
}

function getBestResults(scores, highScore){
  var highestSolution = [];
  for (var i = 0; i < scores.length; i++){
    if (scores[i] == highScore) {
      highestSolution.push(i);
    }
  }
  return highestSolution;
}
var highestSolution = getBestResults(scores, highScore);
console.log("編號" + highestSolution + "得最高分")
//"編號0,2得最高分"


var costs = [.25, .27, .33, .29, .27, .22];
function getBestSolution(scores, costs, highScore){
  var cost = 100;
  var index;
  
  for (var i = 0; i < scores.length; i++) {
    if (scores[i] == highScore) {
      if (cost > costs[i]) {
        index = i;
        cost = cost[i];
      }
    }
  }
  return index;
}
var bestSolution = getBestSolution(scores, costs, highScore);
console.log("編號" + bestSolution + "CP值最高");
//"編號0CP值最高"

我想大家看code也看得很累了(應該是直接跳過吧XD),今天就先這樣啦!

本文同步發表於cichen


上一篇
Day09. 臨兵鬥者皆陣列在前!JavaScript:你錯棚囉!
下一篇
Day11. 你(Ruby)的物件不是我(JavaScript)的物件
系列文
Head First!從頭開始學JS 《深入淺出 JavaScript 程式設計》讀書筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言