作用區域 | 重複宣告 | 重新賦值 | 變數提升 | |
---|---|---|---|---|
var | 函式作用域 | 可 | 可 | 可 |
let | 區塊作用域 | 不可 | 可 | 無 |
const | 區塊作用域 | 不可 | 不可 | 無 |
AI 摘要 「變數提升」(Hoisting)是指在編譯階段, JavaScript 引擎會將 var 宣告的變數提升(移動)到其作用域的頂端, 但只提升宣告本身,不會執行初始化(賦值)動作。 因此,在變數實際被賦值之前呼叫它,值會是 undefined,而不是執行時期報錯。 函式作用域(Function Scope)指的是變數的可存取範圍被限制在某個函式內部, 僅在該函式執行時有效。 在JavaScript 中, 使用 var 關鍵字宣告的變數就具有函式作用域的特性。 這表示在函式外部宣告的變數是全域的,而函式內部的變數則被限制在該函式內部, 無法在外部存取。2.賦值運算
let a = 0; a = a + 50 ; a += 50 ; //等同於上方算式
let a = 0 ; a += 1; a ++ ; //等同於上方算式3.字串 string
let s1 = 's1' ; //單引號 let s2 = "s2" ; //雙引號 let go = "let's go"; //基本上一樣,看需求使用 let name = "Marco" ; let content = "Hello"; console.log(name + content);//字串相加
let name = " Maroco "; console.log(name.length); //字串長度 name = name.trim(); //濾掉前後空白 console.log(name.length);
let name = "Maroco"; let age = 19; console.log(`您好我叫${name},今年${age}歲`);4.typeof(型別)
let a = 1 ; console.log(typeof a); //number let b = "哈" ; console.log(typeof b); //string
let a = 1 ; let b = "哈" ; let c = a + b ; console.log(c); // 1哈 console.log(typeof c); //字串跟數字相加會變成字串
let a = 1 ; let b = "哈" ; let d = a * b ; console.log( d);//NaN 非數字進行運算 console.log(typeof d);// number5.布林
let is = 2 > 3; // ture or false console.log(is); // false console.log(typeof is); // boolean6.undefined 尚未被賦於值
let u; console.log(u); // undefined console.log(typeof u); // undefined7.null 有被賦於值,後清空
let n = [];//內容假裝很多 n = null;//清空記憶體8.字串轉文字parseInt、parseFloat
let s1 = "哈哈"; s1 = parseInt(s1); console.log(s1); // NaN
let s2 = "123"; //從表單抓取資料都是字串所以要轉型 s2 = parseInt(s2); //parseFloat()有小數點 console.log(s2); // 1239.數字轉字串
let s3 = 123; s3 = s3.toString(); console.log(s3); // 123 console.log(s3 + 9); // 1239 字串+數字= 字串 console.log(typeof s3) //string10.陣列
//[]陣列 const colors = ["yellow", "red", "blue"]; const any = [123, true, "Tom"];//可混合 console.log(`colors陣列共用${colors.length}筆`); let myColor = colors[2]; //讀取陣列,陣列從從0開始算 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.push("black"); console.log(colors);//["blue","yellow",null,"red","black"];11.物件
//物件{} const family = { myFather: "David",//屬性 : 值 myMonther: "Mary",//屬性 : 值 dogs: 3 }; console.log(family.myFather); //讀取物件中屬性
//寫入 let home = {}; home.myMonther="May"; home.myFahter ="Kevin"; home.cats = 4; console.log(home); //{"myMonther": "May","myFahter": "Kevin", "cats": 4}參考資料
六角線上課
JS 宣告變數, var 與 let / const 差異