/** * 五種基本數據類型:string, number, boolean, null, undefined */ // undefined // 聲明變量foo,未聲明變量bar var foo; console.log(`typeof foo: ${foo}`, `typeof bar: ${bar}`); // typeof foo: undefined typeof bar: undefined if (foo === undefined) { // foo全等於undefined console.log('foo全等於undefined'); } else { console.log('foo不全等於undefined'); } if (typeof bar === 'undefined') { // bar全等於undefined console.log('bar全等於undefined'); } else { console.log('bar不全等於undefined'); } // typeof 返回字符串類型 console.log(`typeof (typeof foo): ${typeof (typeof foo)}`); // typeof (typeof foo): string // 定義函數f()但沒有函數體,默認為undefined function f() { } console.log(`typeof f(): ${typeof f()}`, `f() === undefined: ${f() === undefined}`); // typeof f(): undefined f() === undefined: true // null console.log(`typeof Null: ${typeof Null}`); // typeof Null: undefined console.log(`typeof null: ${typeof null}`); // typeof null: object // string // 常用轉義字符 // --------------------------------------------------------------------------- // \n 換行 // \t 制表符 // \b 空格 // \r 回車 // \f 換頁符 // \\ 反斜杠 // \' 單引號 // \" 雙引號 // \0nnn 八進制代碼 nnn 表示的字符(n 是 0 到 7 中的一個八進制數字) // \xnn 十六進制代碼 nn 表示的字符(n 是 0 到 F 中的一個十六進制數字) // \unnnn 十六進制代碼 nnnn 表示的 Unicode 字符(n 是 0 到 F 中的一個十六進制數字) // --------------------------------------------------------------------------- var foo = 'hello'; console.log(`typeof foo: ${typeof foo}`); // typeof foo: string // boolean var right = true, wrong = false; console.log(`typeof right: ${typeof right}, typeof wrong: ${typeof wrong}`); // typeof right: boolean, typeof wrong: boolean // number // 整型 var foo = 100; console.log(`typeof foo: ${typeof foo}`); // typeof foo: number // 八進制 var foo = 017; console.log(foo); // 15 // 十六進制 var foo = 0xAB; console.log(foo) // 171 // 浮點數 var foo = 23.01; console.log(foo); // 23.01 // 最大值 console.log(`Number.MAX_VALUE = ${Number.MAX_VALUE}`); // Number.MAX_VALUE = 1.7976931348623157e+308 // 最小值 console.log(`Number.MIN_VALUE = ${Number.MIN_VALUE}`); // Number.MIN_VALUE = 5e-324 // 正無窮大 console.log(`Number.POSITIVE_INFINITY = ${Number.POSITIVE_INFINITY}`); // Number.POSITIVE_INFINITY = Infinity // 負無窮大 console.log(`Number.NEGATIVE_INFINITY = ${Number.NEGATIVE_INFINITY}`); // Number.NEGATIVE_INFINITY = -Infinity // isFinite 驗證是有限數字 var foo = Number.POSITIVE_INFINITY, bar = foo * 3; if (isFinite(bar)) { // bar是無窮大數字 console.log('bar是有限數字'); } else { console.log('bar是無窮大數字'); } // NaN 不是一個數字,特殊數值,不可用於直接計算 var foo = 'hello'; if (isNaN(foo)) { // foo不是數字 console.log('foo不是數字'); } else { console.log('foo是數字'); }