2025年10月17日 星期五

筆記 JavaScript 工程師養成直播班 第六堂

1.HTTP 回應狀態碼
資訊回應(100——199)
成功回應(200——299)
重新導向訊息(300——399)
用戶端錯誤回應(400——499)
伺服器錯誤回應(500——599)
2.常見回應狀態碼
200 OK
請求成功。「成功」的結果含義取決於 HTTP 方法:
GET:資源已被擷取並在訊息主體中傳送。
Headers:回應中包含表示標頭,但沒有任何訊息主體。

PUT 或 POST:描述操作結果的資源在訊息主體中傳送。
TRACE:訊息主體包含了伺服器接收到的請求訊息。

304 Not Modified
記憶體有快取未被修改

404 Not Found
只不到網頁

500 Internal Server Error
後端程式有問題
3.request(請求)
Clinet > Server > DB
request header content-type:解析格式
request data
3.reponse(回傳)
DB > Server > Clinet
response header content-type:解析格式
response data
4.Javascript 原生寫法
1.XMLhttpRequest
2.Fetch
5.axios(底層用XMLhttpRequest)
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
6.同步、非同步
同步:順序性執行A -> B -> C
非同步:同時執行不會卡住,網路請求、計時器、檔案讀取,處裡須等待佳
A ->
B ->
C ->
7.處理非同步問題
非同步不會等待,所以有可能沒有資料時就跑下面的js,處理方式可以包在函式中
8.HTTP Method
get 獲取
post 新增
delete 刪除
put 更新
patch 修改一部分

差別除Get以外其他可傳送資料給伺服器
9.傳遞資料正確API才有用
傳送
1.Method
2.URL
3.資料正確
接收
1.看規格
10.常用的資料請求格式Content-Type:
1.application/x-www-form-urlencoded form表單
2.application/json JSON
3.multipart/form-data 檔案、圖片、影片
4.text/plain 純文字
11.axios.get
	console.log(axios);//可以看看有沒有載入成功
	axios.get('網址')
	.then(function (response) {
		console.log(response);
	})
	.catch(function (error) {
		console.log(error);
	})
	.finally(function () {
		// 均會執行
	});
12.開發除錯概念
POST網址可能會跑兩次 
F12開發工具 > NetWork > preflight-先驗證是否為跨網域 > xhr-可跨網域才送出請求 
F12開發工具 > NetWork > 網頁 > Headers 傳送的狀態
F12開發工具 > NetWork > 網頁 > Payloads 傳送的資料
F12開發工具 > NetWork > 網頁 > Response 回傳的資料
13.直播補充
舊方式:Form
缺點:整頁刷新 > 中斷使用者操作 > 短暫空白

新方式:AJAX
支援非同步機制 > 頁面局部更新 > 不必重整整個頁面 
伺服器回傳資料 > 不會轉址 > 決定可更新哪個畫面
優點:減少data傳輸,載入速度,使用者操作更順暢
缺點:無法預期完成順序

一定走非同步:均須等待時
1.網路請求
2.計時器 setTimeout(function(){},1000);
3.檔案讀取
參考來源
六角學院直播課
HTTP 回應狀態碼

2025年10月8日 星期三

筆記 JavaScript 工程師養成直播班 第五堂

1.認識DOM(Documnet Object Model)標籤
documnet
Elemnet : <a></a>  
Attribute : "href"
Text : <a>mylink</a> (mylink)
2.網頁解析由上而下
<script>javascript 語法</script>
JS建議放於網頁下面等DOM解析完成使用才不會有問題
3.querySelector(選取第一個符合元素)(沒符合null)
    <h1 class="header">1234</h1>     
    <script>        
        const el = document.querySelector('.header');        
        console.log(el);//<h1 class="header">1234</h1>
    </script>
    
    <div class="targetBElementP">
 	 <p>請選取我</p>
    </div>    
    <script> 
    	//取得child
    	const targetBElementP = document.querySelector(".targetBElementP > p");
    </script>
    
    //以下較舊可不使用
    getElementsByClassName('.class');
    getElementsByTagName('tag');
    getElementById('#id');
4.元素加入HTML或文字(innerHTML刪除內容後再加入)
    <main>123</main>
    <script>
       const main =  document.querySelector('main');
       main.innerHTML =`<h1>546</h1>`;//加入html標籤
       const h1 = document.querySelector('h1');
       console.log(h1);//<h1>456</h1>
    </script>
5.元素插入html或文字(prepend、append、appendChild)
    <ul>
        <li>hihi</li>
    </ul>
    <script>
        const ul = document.querySelector('ul');         
        const liappendChild = document.createElement('li');
        liappendChild.textContent = "我是appendChild加入的我會新增在後面";
        ul.appendChild(liappendChild);
        const liprepend = document.createElement('li');
        liprepend.textContent = "我是prepend加入的我會新增在最前面";
        ul.prepend(liprepend);
         const liappend = document.createElement('li');
        liappend.textContent = "我是aappend加入的我會新增在後面";
        ul.append(liappend);
    </script>
6.innerHTML、textContent差異
    <main></main>
    <script>
       const main =  document.querySelector('main');
       main.innerHTML =`<h1>123</h1>`;//html標籤
       main.textContent=`<h1>123</h1>`;//會是文字
    </script>
7.querySelectorAll,回傳NodeList陣列(沒符合null)
    <a>Google</a>
    <a>Yahoo</a>
    <script>
        const myLinks = document.querySelectorAll('a');//會回傳NodeList陣列
        console.log(myLinks);
        myLinks[0].setAttribute("href", "https://www.google.com");
        myLinks[1].setAttribute("href", "https://tw.yahoo.com");
    </script>
8.setAttribute加入屬性,getAttribute取得屬性
    <a></a>
    <script>
        const myLink = document.querySelector('a');
        myLink.innerHTML = "<span>Google</sapn>";
        //設定Attribute
        myLink.setAttribute("href", "https://www.google.com");
        myLink.setAttribute("target", "_blank");
        myLink.setAttribute("id", "x123");
        //取出設定Attribute
        console.log(myLink.getAttribute("href"));//https://www.google.com
        console.log(myLink.getAttribute("target"));//_blank
        //刪除Attribute
        myLink.removeAttribute("id");
    </script>
9.表單元素取值、賦值
    <input type="text" class="txt" value="早安" />
    <select class="list">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
    <script>
        const txt = document.querySelector('.txt');
        console.log(txt.value);//早安
        txt.value = "晚安"; //賦值
        console.log(txt.value);//晚安

        const list = document.querySelector('.list');
        console.log(list);//<select class="list"><option value="1">1</option><option value="2">2</option></select>
        console.log(list.value);//1
        list.value = 2; //賦值
        console.log(list.value);//2
    </script>
10.classList+style應用
    <style>
        main {
            width: 300px;
            height: 300px;
            background-color: lightblue;
        }

        .box1 {
            width: 100px;
            height: 100px;
            background-color: blue;
        }

        .box2 {
            width: 100px;
            height: 100px;
            background-color: yellow;
        }

        .active {
            width: 250px;
            height: 250px;           
        }
    </style>
    
    <main>
        <div id="div1">JS加入Class</div>
    </main>
    <script>
        const main = document.querySelector('main');
        const div1 = document.querySelector('#div1');
        //add加入
        div1.classList.add('box1');

        //remove移除
        //div1.classList.remove("box1");
        
        //replace替換
        div1.classList.replace("box1", "box2");

        //toggle切換
        div1.classList.toggle('active');
        //div1.classList.toggle('active');

        //有多少個 class
        console.log(div1.classList.length);

        //contains包含
        if (div1.classList.contains("box2")) {
            console.log("有box2");
        } else {
            console.log("沒有box2");
        }

        //直接修改 style    
        div1.style.backgroundColor = 'green';
        div1.style.color = 'white';
        div1.style.fontWeight = 'bold';
        div1.style.fontSize = '64px';
    </script>
11.data attribute (setAttributeget、getAttribute也可做到)
     <main>
          <div id="div1" data-username="John"> JS加入 data attribute 建議小寫</div>
     </main>
     <script>
          const main = document.querySelector('main');
          const div1 = document.querySelector('#div1');
          //取得 data attribute        
          //div1.setAttribute('data-username', 'Tom');// set tom
          console.log(div1.dataset.username);//john

          //修改 data attribute
          div1.dataset.username = 'Mary';
          //console.log(div1.getAttribute('data-username'));//Mary
          console.log(div1.dataset.username);//Mary

          //設定 data attribute (特殊字元時為小駝峰)
          div1.dataset.userId = 123; //dataset.userId => data-user-id
          console.log(div1.dataset.userId); //123

          //刪除 data attribute,可用delete or removeAttribute
          //delete div1.dataset.userId;//dataset.userId => data-user-id
          div1.removeAttribute('data-user-id');
          console.log(div1.dataset.userId); //undefined

     </script>
12.addEventListener註冊監聽事件
是否有註冊監聽,chrome > F12 > 元素上檢查 > Even Listeners
    <ul class="list">
        <li><span>hihi</span></li>
        <li>hihi <input type="button" value="按鈕" class="btn"></li>
    </ul>
    <h1></h1>
    <script>
        const btn = document.querySelector('.list');
        //const btn = document.querySelector('.btn');        
        const h1 = document.querySelector('h1');
        let count = 0;
        btn.addEventListener('click', function (e) {
            if (e.target.nodeName == "INPUT") {
                //btn.addEventListener('click', function (e) {
                count++;
                h1.textContent = `手速測試,您點擊了${count}次`;
            } else {
                console.log(e);//捕捉當下元素資訊
                console.log(e.clientX);
                console.log(btn.nodeName);//INPUT 目前的元素tag
                console.log(e.target);//偵測到目前點擊是哪個元素
                console.log(e.target.nodeName);//INPUT          
                console.log(e.target.innerHTML);
                console.log(e.target.textContent);
                h1.textContent = `點到${e.target.nodeName}`;
            }
        });
    </script>
13.preventDefault取消預設觸發行為
    <a href="http://tw.yahoo.com">yahoo</a>
    <script>
        const myLink = document.querySelector('a');
        myLink.addEventListener('click', function (e) {
            e.preventDefault();
            console.log('有點點到,但不會轉址');
        });
    </script>
參考資料
六角學院直播課
你需要注意的 console.log 問題

2025年10月3日 星期五

筆記 JavaScript 工程師養成直播班 第四堂

1.函式(function)宣告方式及用法
//函式屬於物件型別
//程式碼重複使用
function 函式名稱(參數){
	//要執行的程式碼
}
函式名稱(參數);
2.執行順序
happy();
holiday();
先執行happy()程式碼法,後再執行holiday()內程式碼
3.函式包函式順序
        function first() {
            console.log('first');
            third();
        };
        function second() {
            console.log('second');
        };
        function third() {
            console.log('third');
        };

        first();
        second();
        third();

        //  first
        //  third
        //  second
        //  third
4.函式帶入參數,只會在大括號裡面使用,執行完就消失
        function callNum(num) {
            console.log(`呼叫${num}號`)
        }
        callNum(5); // 呼叫5號
        console.log(`呼叫${num}號`); // num is not defined
5.函式可帶入多個參數
        function addNum(num1, num2) {
            console.log(num1 + num2);//3
        }
        addNum(1, 2);
6.return可回傳值
        function addNum(num1, num2) {
            return num1 + num2; 
        }
        const result = addNum(1, 2);
        console.log(result);//3
7.return 會中斷函式
        function addNum(num1, num2) {
            console.log(1);//1
            return num1 + num2;
            console.log(2);//沒跑
        }
        const result = addNum(1, 2);
        console.log(result);//3
8.return 多個值,回傳array或物件
        function addNum(num1, num2) {
            return [num1 , num2];
        }
        const result = addNum(1, 2);
        console.log(result); //[1,2]
9.函式種類
        console.log(numA(3));
        //函式陳述式(不管放在哪裡都可以執行)
        function numA(x) {
            return x * x;
        }

        //函式表達式
        //console.log(numB(3)); //變數numB賦值前就使用,無法讀取該變數
        const numB = function (x) {
            return x * x;
        }
        console.log(numB(3)); //必須在賦值後才能使用

        //箭頭函式       
        //函式表達式(function (x))、箭頭函式((x) =>)一樣的
        const numC = (x) => {
            return x * x;
        }
        console.log(numC(3));

        //箭頭函式更精簡寫法
        //必須有retrun,大括號及return可不寫
        //只有一個參數時可省略(x)=>變成x =>
        //如果沒有參數時寫()=>
        const numD = (x) => x * x;
        console.log(numD(3));
參考資料
六角學院直播課

2025年10月1日 星期三

筆記 JavaScript 工程師養成直播班 第三堂

1.陣列 (物件型別)
        //[]陣列
        //只有值,可包任何型別
        //取值用索引,順序很重要因為要知道第幾個才能取
        const colors = ["yellow", "red", "blue"];
        const any = [123, true, "Tom"];//可混合 
        //length 長度
        console.log(`colors陣列共用${colors.length}筆`);
        //讀取陣列,陣列從從0開始算 
        let myColor = colors[2];
        console.log(myColor); // "blue"
        myColor = colors[3]; //陣列從0開始 
        console.log(myColor); // undefined
 
        //陣列資料應用
        let colors = [];
        colors[0] = "blue";
        colors[1] = "yellow";
        colors[3] = "red";
        console.log(colors);//["blue","yellow", null,"red"]
        console.log(`colors陣列共用${colors.length}筆`); //colors陣列共用4筆       

        //unshift 加入第一筆
        colors.unshift("green");
        console.log(colors);//["geeen","blue","yellow",null,"red"];

        //push 加入最後一筆
        colors.push("black");
        console.log(colors);//["geeen","blue","yellow",null,"red","black"];        

        //pop 刪除第一筆
        colors.shift();
        console.log(colors);//["blue","yellow",null,"red","black"];

        //pop 刪除最後一筆
        colors.pop();
        console.log(colors);//["blue","yellow",null,"red"];

        //splice 刪除指定資料
        //splice(1 , 2) splice(起始位置(陣列從0開始) , 2(往後刪除幾筆)) 
        colors.splice(1, 2);
        console.log(colors);//["blue","red"];    

        //splice 插入指定資料 第二參數為0
        colors.splice(1, 0, "gold");
        console.log(colors);//["blue","gold","red"]; 

        //splice 修改指定資料 第二參數為1
        colors.splice(1, 1, "white");
        console.log(colors);//["blue","white","red"]; 

        const data = [1, 3, 9, 5, 7, 9];
        //map() 方法會建立一個新的陣列(不影響原始資料)
        const arr1 = data.map(x => x * x);
        console.log(arr1);//[1,9,81,25,49,81]

        //forEach() 不會回傳值
        data.forEach(function(item,index,array){
            //item 目前資料
            //index 目前索引
            //array 目前所有陣列
            console.log(item,index,array);
        });
        const arr2 = [];
        data.forEach(x => { arr2.push(x * x); });
        console.log(arr2);//[1,9,81,25,49,81]

        //filter() 篩選出符合條件回傳新的陣列(不影響原始資料),查無空陣列
        const arr3 = data.filter(x => x >= 5);
        console.log(arr3);//[9,5,7,9]

        //find() 由前往後符合的第一筆,查無undefined
        const obj4 = data.find(x => x >= 5);
        console.log(obj4);//9 

        //indexOf 由前往後符合的第一筆,-1查無
        const i5 = data.indexOf(9);
        console.log(i5);//2 [1 3 9這筆, 5, 7, 9]

        //lastIndexO 由後往前符合的第一筆,-1查無
        const i6 = data.lastIndexOf(9);
        console.log(i6);//5 [1, 3, 9, 5, 7, 9這筆]

        //reduce() 方法將一個累加器及陣列中每項元素(由左至右),將陣列化為單一值。
         const i7 = data.reduce((a, b) => {
            //console.log(a,b);//a 累加後的值 b目前進來運算的值
            return a + b;
        }, 0); //'0' 是累加器的初始值
        console.log(i7);//34
        console.log ( data.reduce((a, b) => a + b, 0));//簡寫
        
        //sort() 排序
        //reverse() 反排序        
        //join() 變字串     
        //some() 一個值符合條件回傳true
        //every() 陣列完全符合條件true   
        //slice() 淺拷貝至新物件
        //concat() 合併
2.物件 (物件型別)
        //物件{}
        //屬性:值
        //取值用屬性,順序不重要只要知道屬性就能取值
        const family = {
            myFather: "David",//屬性 : 值
            myMonther: "Mary",//屬性 : 值
            dogs: 3
        };
        console.log(family.myFather); //讀取物件中屬性
 
        //物件資料應用
        let home = {};
        //新增、修改        
        //點記法 (Dot notation)
        home.myMonther = "May";
        home.myFahter = "Kevin";
        home.cats = 4;
        console.log(home);  //{"myMonther": "May","myFahter": "Kevin", "cats": 4}
        home.cats += 1;
        home.myMonther = "Tom";
        console.log(home);  //{"myMonther": "Tom","myFahter": "Kevin", "cats": 5}
        //刪除
        delete home.cats;
        console.log(home);  //{"myMonther": "Tom","myFahter": "Kevin"}
        console.log(home.cats); //undefined
        //讀取方式
        //括弧記法 (Bracket notation),屬性特殊字元時必須使用
        let f = "001";//特殊開頭為數字時
        home[f] = "1234"       
        console.log(home[f]);//"Kevin"
3. ... Spread Operator Rest Operator
     <script>

          // ...用法
          //展開運算符 Spread Operator 
          //1.淺拷貝及合併    
          const arr1 = [1, 2, 3];
          const arr2 = [...arr1];
          arr2.push(4);
          console.log(arr1, arr2);//[1, 2, 3] , [1, 2, 3, 4]
          const arr3 = ["Good", "Morning"];
          const arr4 = [...arr3, "Teacher"];
          console.log(arr4); //['Good', 'Morning', 'Teacher']
          //2.直接傳入函式中,
          function sum(a, b) {
               return a + b;
          }
          const arr5 = [1, 2, 3];//函式如果只有兩個參數傳入第三個時會忽略
          console.log(sum(...arr5)); // 3
          //3.可迭代(iterable)物件轉陣列,String、Array、TypedArray、Map、Set物件
          const str1 = "Today in Monday";
          const arr6 = [...str1];
          console.log(arr6);//[ "T","o","d","a","y"," ", "i", "n", " ", "M", "o", "n", "d", "a", "y"]

          //其餘運算符 Rest Operator        
          function sumAll(...numbers) {
               return numbers.reduce((a, b) => a + b, 0);
          }
          console.log(sumAll(1, 2, 3, 4)); // 10
          console.log(sumAll(5, 10, 15));  // 30   
     </script>
4.JSON(Javascript Object Notaion)(JS物件表示法)
1.屬性都是字串 "data" : [] ;
2.沒辦法放函式
3.不能註解
4.最後一個值後面不能加入逗號
5.目前前後端常用資料傳遞格式
5.補充
陣列第幾筆用[]中間數字
物件找值用.屬性
6.chrome擴充套件
JSONView
參考資料
六角學院直播課
Day 09: ES6篇: Spread Operator & Rest Operator(展開與其餘運算符)