2017年6月19日 星期一

[JS]網頁學習 第一章 JS Array Sort 小節 問題

以下引用 w3school 網站內文

The Compare Function
The purpose of the compare function is to define an alternative sort order.

The compare function should return a negative, zero, or positive value, depending on the arguments:

function(a, b){return a-b}

唸到這邊非常卡:

1. a, b 是什麼?
並無宣告 var a, b,所以是預設 Arrays 中的每個 element 嗎?

2. 為何 a - b < 0 則 a 就排序在 b 前面,也是預設嗎?
return 結果可為負數、0、正數,分別如何影響排序?

3. 為何改為 return b - a 就是從大到小排序?

4. 為何改為 return 0.5 - Math.random() 就是亂數?不需要用到 a, b了嗎?


----

var points = [40, 100, 1, 5, 25, 10];

document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
    return Math.max.apply(null, arr);

}

null 的作用是? 為何將 Math.max.apply() 參數去掉或打錯就變 -Infinite?

----

<h2>JavaScript Array Sort</h2>

<p>Click the buttons to sort car objects on age.</p>

<button onclick="myFunction()">Sort</button>

<p id="demo"></p>

<script>
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}]

displayCars();

function myFunction() {
    cars.sort(function(a, b){return a.year - b.year});
    displayCars();
}

function displayCars() {
  document.getElementById("demo").innerHTML =
  cars[0].type + " " + cars[0].year + "<br>" +
  cars[1].type + " " + cars[1].year + "<br>" +
  cars[2].type + " " + cars[2].year;
}

</script>

上述是依照年份排列,改成依 type 字母排序,
想取出各 element 的 type 再以 charAt(0) 比較,
  cars.sort(this.type.charAt(0));
測試結果無法將 type 依序排列,why ?

沒有留言:

張貼留言