2017年6月29日 星期四

[JS]網頁學習 第五章 DOM Events, DOM Events Listener 小節 心得小記

Events 這節教一個實作法:

document.getElementById("myBtn").onclick = displayDate;

看似很方便,但會導致程式 runtime 變長吧?
----

實作範例錯誤集:

<button onclick=myFunction>Click Me</button>

<span onMoveover="this.style.color='red'">Mouse over me!</span>

還有疑似錯誤(因結果跑得出來,但程式碼與正解不同):

document.getElementById("myBtn").onclick = displayDate;
----

解答:

<button onclick="myFunction()">Click Me</button>

<span onmouseover="this.style.color='red'">Mouse over me!</span>

document.getElementById("myBtn").onclick =
function(){displayDate()};

----

Events Listener 小節有個酷炫的範例,
隨著視窗被調整改變顯示的文字:

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

<script>
window.addEventListener("resize", function(){
    document.getElementById("demo").innerHTML = Math.random();
});

</script>


[JS]網頁學習 第五章 DOM Elements, DOM CSS 小節 心得小記

在範例練習中,寫錯成;

<p>Use the DOM to change my text!</p>

<script>
document.getElementsByTaName("p").innerHTML = "Change"
</script>
----

  <head>
    <title>W3Schools Demo</title>
  </head>
<body>

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

<script>
document.getElementById("demo").innerHTML =
"The title of this document is: " +
document.getElementByTagName("title")[0].innerHTML ;
----

<p id="demo">Hello World!</p>

<script>
document.getElementById("demo").style.backgroundcolor = yellow;
</script>

在此紀錄犯過的錯誤,



正解為:

document.getElementsByTagName("p")[0].innerHTML = "Change"
----

document.getElementById("demo").innerHTML =
"The title of this document is: " +
document.title ;
----

document.getElementById("demo").style.backgroundColor = "yellow";

[JS]網頁學習 第四章 Function Closures小節 心得小記

本節先說明 local variable & global variable,
而後解釋 closure。

<button type="button" onclick="myFunction()">Count!</button>

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

<script>
var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>

以下是網站解釋:

The variable add is assigned the return value of a self-invoking function.

The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.

This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope.

This is called a JavaScript closure. It makes it possible for a function to have "private" variables.

The counter is protected by the scope of the anonymous function, and can only be changed using the add function.

紅字不懂啊!

2017年6月28日 星期三

[JS]網頁學習 第四章 Function Definitions, Function Parameters小節 心得小記

原來 Hoisting 也適用 function,
所以才會出現先有 function( ); 後面才宣告該 function 執行碼。

myFunction(5);

function myFunction(y) {
    return y * y;
}

但這樣是個好的寫法嗎?
----

以下認知待商榷:

未被呼叫的 function,其參數稱為 parameters;
被呼叫的 function,其參數稱為 arguments。

method 是長的像 function 的 property。


[JS]網頁學習 第三章 Object Methods, Object Prototypes小節 心得小記

總覺得這是一個很好的參考範例,使用到 this 及帶有參數的 function,
因此特別收錄,以便隨時參閱:

<script>
function person(firstName,lastName,age,eyeColor) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.eyeColor = eyeColor;
    this.changeName = function (name) {
        this.lastName = name;
    }
}
var myMother = new person("Sally","Rally",48,"green");
myMother.changeName("Doe");
document.getElementById("demo").innerHTML =
"My mother's last name is " + myMother.lastName;
</script>
----

講述 prototype 若要新增新的 property/ method 不可使用如下
(新增一般已存在物件的syntax):


Person.nationality = "English";

因 prototype 並非已存在物件,而是建構子;
若要新增,則要在定義 prototype 區塊寫入。

但是允許以下作法,使用 prototype property:

Person.prototype.nationality = "English";
Person.prototype.name = function() {
    return this.firstName + " " + this.lastName;
};

2017年6月27日 星期二

[JS]網頁學習 第二章 JS Forms, Forms API 小節 心得小記

說明、舉例驗證 user input,避免無填入或範圍外的數值,
這裡提到經常使用在檢驗數字。

輸入錯誤可選擇顯示跳出視窗,或是在 input 附近提示。
驗證無填入、跳出視窗:

<script>
function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == "") {
        alert("Name must be filled out");
        return false;
    }
}
</script>
</head>
<body>

<form name="myForm" action="/action_page_post.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>


</body>

以上畫紅字不懂:
1. 為何不可刪除 ["myForm"]?
2. 輸入 false 是為了停止繼續執行?
3. 可以使用 onclick 嗎?

試著將var x 改為常用的 getElementById("fname")、
onsubmit 改為 onclick 並移至 input type="submit" 中,
完全錯誤不驗證跳下一頁!why~

另外,document.forms[][] 好像是第一次出現,留意一下這個句型。

2017年6月26日 星期一

[JS]網頁學習 第一章 JS RegExp, JS Performance, JS JSON 小節 心得小記

使用 RegExp 來搜尋字串,
若 modifier 設 i ,則搜尋無大小寫之分。

----

接近第一章尾聲,
開始講解如何撰寫是較佳的句型,使程式更有效率,
是很實用也很貼心的數個小節,而非我原以為的行數越少越好:

Bad:
var i;
for (i = 0; i < arr.length; i++) {
Better Code:
var i;
var l = arr.length;
for (i = 0; i < l; i++) {

----

<h2>Create Object from JSON String</h2>

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

<script>
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>

上例用 JSON 編寫,但又為何要多此一舉用 JSON 呢?
可能後面章節會說明,先在此紀錄問題。

2017年6月22日 星期四

[JS]網頁學習 第一章 JS Type Conversion, JS Bitwise 小節 心得小記

最喜歡樹狀圖 & 條列式了!
以下引用網頁內文,type們的彙整:

In JS there are 5 different data types that can contain values:

  •   string
  •   number
  •   boolean
  •   object
  •   function

There are 3 types of objects:

  • Object
  • Date
  • Array

And 2 data types that cannot contain values:

  • null
  • undefined
----

這個章節出現一個回傳並印出 "true" 的範例,在此練習解釋:

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = isArray(fruits);

function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}
</script>

在 id = "demo" 的標籤加入 isArray(fruits) method 的回傳值,
所以要解釋 isArray():
isArray(example) 回傳括弧中參數 example 的 constructor 為何種型別方法,
並將回傳結果顯示為字串 (string? array?),
indexOf使得若字串 (string? array?) 中有 "Array" 字串,則 indexOf 必大於等於0,
故 > -1 為 true.


以上除了 (string? array?),其他都較有把握解釋正確。
這邊將腳本碼改成下述也是回傳 true,意義應該相同:(待高人指點)

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = 
(fruits.constructor.toString().indexOf("Array") > -1);
</script>

網頁中還有更簡化的範例,使用到" === ",也不難該試著想想看。

----

Bitwise 的章節,以下範例有疑問:
Converting Decimal to Binary
Example

function dec2bin(dec){
    return (dec >>> 0).toString(2);
}

dec >>> 0 表示什麼?將參數補0右移0個位子?
toString(2) 的2表示2進位嗎?

2017年6月21日 星期三

[JS]書面學習 犀牛書 第一部第一至四章 心得小記

第一章

在 12頁時放上一個貸款計算的範例,

這時才知道, canvas 的功能發揮在此:

使用者填入資訊 (本金、利率、分期數),
canvas 汲取資訊繪出圖樣 (償貸交叉圖表)

因先前的書都是在程式碼中繪成的範例,
所以後知後覺發現是這樣厲害的功能!

----

第三章

型別「只有」兩種:primitive type, object type。
非 primitive type 則 object type,有非p則q的感覺。
primitive type : numbers, strings, Boolean, (null and undefined)

實務上對 null 使用 typeOf operator 會回傳 "object",
null 被看成自成一型別,它是這個型別的唯一成員。

對 undefined 使用 typeOf operator 會回傳 "undefined",
也是自成一型別的唯一成員。

物件導向語言的解釋
「JS是物件導向語言,
粗略地說,代表型別它們自己可以定義 methods 來處理 values(運算值),
而非使用一個 global function 去處理各種型別的運算值。
例如:

   使用 a.sort() // invoke a 的 method,
   而不是使用 sort(a) // 把 a 傳給一個 sort() 函式。」--第30頁


型別分類除了基本型別與物件型別,
也可分為有方法與沒方法 (
null and undefined) 的型別;
還可分為可變與不可變的型別
primitive type 屬 immutable,
object type 則 mutable。

2017年6月20日 星期二

[JS]網頁學習 第一章 JS Array Sort 小節 進度紀錄

用網站學有點吃力,晚上看螢幕也覺得很刺眼,
試著改成網站 ( w3school JS ) + 書目 ( 犀牛書! ) 雙管齊下,所以時間要重新設定。

網站進度原訂 6/30,目前已落後 2日份量;

犀牛書大約 1000頁,與 HF 系列排版不同,字較密集,留白、圖片較少
加上工作關係,應該最快也要 15天才能讀完。

皆以扣除假日、工作時數計算:

改成 w3school 網站研讀量每日減半為 4p / d,日期拉長至 7/15,
犀牛書若要 15日看完,需在工作最鬆的情況,先估計 20日,7/11 ( 50p / d )。

若能維持至少 w3school 4p / d,則能在 7/11 與犀牛書同步完成。

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 ?