ES6–ES12筆記整理(1)

一、let const

五個共同特點

  1. 不允許重複聲明
  2. 塊級作用域
  3. 不存在變數提升
  4. 不影響作用域鏈
  5. 暫時性死區—在程式碼塊內,使用let/const命令聲明變數之前,該變數都是不可用的。這在語法上,稱為「暫時性死區」

const 特殊性

  1. 聲明必須賦初始值;
  2. 標識符一般為大寫(習慣);
  3. 值不允許修改;
  • 指向的那個記憶體地址所保存的數據不得改動。
  • 對於簡單類型的數據(數值、字元串、布爾值),值就保存在變數指向的那個記憶體地址,因此等同於常量。
  • 對於複合類型的數據(主要是對象和數組),變數指向的記憶體地址,保存的只是一個指向實際數據的指針,const只能保證這個指針是固定的(即總是指向另一個固定的地址),至於它指向的數據結構是不是可變的,就完全不能控制了。

二、解構賦值

允許按照一定模式,從數組和對象中提取值,對變數進行賦值,這被稱為解構

  1. 數組的解構賦值
  2. 對象的解構賦值
  3. 字元串的解構賦值
  4. 數值和布爾值的解構賦值
  5. 函數參數的解構賦值

1、數組的解構賦值

數組的元素是按次序排列的,變數的取值由它的位置決定

let [a, b, c] = [1, 2, 3];

let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3

默認值

let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'

2、對象的解構賦值

對象的屬性沒有次序,變數必須與屬性同名,才能取到正確的值

let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"

let { baz } = { foo: 'aaa', bar: 'bbb' };
baz // undefined

let { first: f, last: l } = { first: 'hello', last: 'world' }
f // 'hello'
l // 'world

const node = {
  loc: {
    start: {
      line: 1,
      column: 5
    }
  }
};

let { loc, loc: { start }, loc: { start: { line }} } = node;
line // 1
loc  // Object {start: Object}
start // Object {line: 1, column: 5}

默認值

var {x, y = 5} = {x: 1};
x // 1
y // 5

注意
(1)如果要將一個已經聲明的變數用於解構賦值,必須非常小心。

// 錯誤的寫法
let x;
{x} = {x: 1};
// SyntaxError: syntax error
// 正確的寫法
let x;
({x} = {x: 1});

3、字元串的解構賦值

  • 字元串也可以解構賦值。這是因為此時,字元串被轉換成了一個類似數組的對象。
  • 類似數組的對象都有一個length屬性,因此還可以對這個屬性解構賦值。
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"

let {length : len} = 'hello';
len // 5

4、數值和布爾值的解構賦值

解構賦值時,如果等號右邊是數值和布爾值,則會先轉為對象。

let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true

5、函數參數的解構賦值

三、字元串擴展

序號 寫法 解釋
1 Unicode 表示法 允許採用\uxxxx形式表示一個字元
2 for of 遍歷 類似於for in ,可以便利原型鏈上的內容
3 字元串 模板字元串:可換行,${}傳參
4 String.fromCodePoint()、ES5 fromCardCode 從 Unicode 碼點返回對應字元
5 String.raw() 返回一個斜杠都被轉義(即斜杠前面再加一個斜杠)的字元串
6 實例方法:codePointAt()、ES5 cardCodeAt() 字元轉code碼
7 實例方法:at(index) 查看指定位置的字元
8 實例方法:includes(), startsWith(), endsWith() 匹配是否存在
9 實例方法:repeat() 將原字元串重複n次
10 實例方法:padStart(),padEnd() 補全
11 實例方法:trimStart(),trimEnd() 消除空格
12 實例方法:replaceAll() 替換所有匹配的內容

1、Unicode 表示法

  • 允許採用\uxxxx形式表示一個字元
  • 限於碼點在\u0000~\uFFFF之間的字元
    "\u{20BB7}"
    // "𠮷"
    
  • JavaScript 共有 6 種方法可以表示一個字元
    '\z' === 'z'  // true
    '\172' === 'z' // true
    '\x7A' === 'z' // true
    '\u007A' === 'z' // true
    '\u{7A}' === 'z' // true
    

2、for of 遍歷

for (let codePoint of 'foo') {
  console.log(codePoint)
}
// "f"
// "o"
// "o"

可以識別大於0xFFFF的碼點

let text = String.fromCodePoint(0x20BB7);

for (let i = 0; i < text.length; i++) {
  console.log(text[i]);
}
// " "
// " "

for (let i of text) {
  console.log(i);
}
// "𠮷"

3、模板字元串

let msg = `Hello, ${place}`;

4、String.fromCodePoint()

從 Unicode 碼點返回對應字元

String.fromCodePoint(0x20BB7)

ES5 提供String.fromCharCode()方法
不能識別碼點大於0xFFFF的字元。

String.fromCharCode(0x20BB7)

5、String.raw()

用來充當模板字元串的處理函數
返回一個斜杠都被轉義(即斜杠前面再加一個斜杠)的字元串,往往用於模板字元串的處理方法

let message1 = `Multiline\nstring`,
console.log(message1); // "Multiline

message2 = String.raw`Multiline\nstring`;
console.log(message2); // "Multiline\\nstring

如果原字元串的斜杠已經轉義,那麼String.raw()不會做任何處理

String.raw`Hi\\n`
// "Hi\\n"

實現方式

String.raw = function (strings, ...values) {
    let output = "";
    let index;
    for (index = 0; index < values.length; index++) {
    output += strings.raw[index] + values[index];
    }
    output += strings.raw[index]
    return output;
}

String.raw方法也可以作為正常的函數使用。這時,它的第一個參數,應該是一個具有raw屬性的對象,且raw屬性的值應該是一個數組

console.log(String.raw({ raw: 'test' }, 0, 1, 2))// 't0e1s2t'
// 等同於
console.log(String.raw({ raw: ['t', 'e', 's', 't'] }, 0, 1, 2))

6、includes(), startsWith(), endsWith()

  • includes():返回布爾值,表示是否找到了參數字元串。
  • startsWith():返回布爾值,表示參數字元串是否在原字元串的頭部。
  • endsWith():返回布爾值,表示參數字元串是否在原字元串的尾部。
let s = 'Hello world!';

s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true

let arr = [1, 2, 3, ]
arr.includes(1) //true

注意:

  • 只針對字元串,數值類型不好用
  • 支援第二個參數,表示開始搜索的位置
let s = 'Hello world!';

s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false

7、repeat()

將原字元串重複n次。

'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""

注意:

  • 參數如果是小數,會被取整。'na'.repeat(2.9) // "nana"
  • 0 到-1 之間的小數,則等同於 0
  • 參數是負數或者Infinity,會報錯
  • repeat的參數是字元串,則會先轉換成數字
    'na'.repeat('na') // ""
    'na'.repeat('3') // "nanana"
    

8、ES7–padStart(),padEnd()

字元串補全長度的功能
字元串不夠指定長度,會在頭部或尾部補全

padStart():用於頭部補全
padEnd():用於尾部補全。

'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'

'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'

參數1:字元串補全生效的最大長度,
參數2:是用來補全的字元串
注意

  • 等於或大於最大長度,則字元串補全不生效,返回原字元串'xxx'.padStart(2, 'ab') // 'xxx'
  • 補全的字元串與原字元串,兩者的長度之和超過了最大長度,則會截去超出位數的補全字元串'abc'.padStart(10, '0123456789')// '0123456abc'
  • 省略第二個參數,默認使用空格補全長度'x'.padStart(4) // ' x'

9、ES9–trimStart(),trimEnd()

與trim()一致消除空格,
trimStart()消除字元串頭部的空格,
trimEnd()消除尾部的空格

10、replaceAll()

替換所有匹配的字元

'aabbcc'.replace('b', '_')
// 'aa_bcc'
'aabbcc'.replace(/b/g, '_')
// 'aa__cc'
'aabbcc'.replaceAll('b', '_')
// 'aa__cc'

11、at()

參數指定位置的字元
支援負索引(即倒數的位置)

const str = 'hello';
str.at[1] // "e"
str.at[-1] // "o"

四、數值擴展

序號 寫法 解釋
1 0b(或0B)和0o(或0O) 二進位和八進位表示法
2 1_000_000_000_000 數值分隔符
3 Number.isFinite(), Number.isNaN() 無窮,非數值類型
4 Number.parseInt(), Number.parseFloat() 整數,小數
5 Number.isInteger() 判斷一個數值是否為整數。
6 Math 對象的擴展
7 BigInt 更長的數據類型

1、二進位和八進位表示法

二進位:前綴0b(或0B)
八進位:前綴0o(或0O)

0b111110111 === 503 // true
0o767 === 503 // true
Number('0b111')  // 7
Number('0o10')  // 8

2、 Number.isFinite(), Number.isNaN()

Number.isFinite()用來檢查一個數值是否為有限的(finite),即不是Infinity
參數類型不是數值,Number.isFinite一律返回false

Number.isFinite(15); // true
Number.isFinite(0.8); // true
Number.isFinite(NaN); // false
Number.isFinite(Infinity); // false
Number.isFinite(-Infinity); // false
Number.isFinite('foo'); // false
Number.isFinite('15'); // false
Number.isFinite(true); // false

Number.isNaN()用來檢查一個值是否為NaN

isFinite(25) // true
isFinite("25") // true
Number.isFinite(25) // true
Number.isFinite("25") // false

isNaN(NaN) // true
isNaN("NaN") // true
Number.isNaN(NaN) // true
Number.isNaN("NaN") // false
Number.isNaN(1) // false

3、 Number.isInteger()

判斷一個數值是否為整數。

Number.isInteger(25) // true
Number.isInteger(25.1) // false
Number.isInteger(25.0) // true
Number.isInteger(null) // false
Number.isInteger('15') // false
Number.isInteger(true) // false

4、Math 對象的擴展

寫法 功能
Math.trunc() 去除一個數的小數部分,返回整數部分
Math.sign() 判斷一個數到底是正數+1、負數-1、還是零0
Math.cbrt() 計算一個數的立方根
Math.hypot(,) 返回所有參數的平方和的平方根
Math.sinh(x) 返回x的雙曲正弦(hyperbolic sine)
Math.cosh(x) 返回x的雙曲餘弦(hyperbolic cosine)
Math.tanh(x) 返回x的雙曲正切(hyperbolic tangent)
Math.asinh(x) 返回x的反雙曲正弦(inverse hyperbolic sine)
Math.acosh(x) 返回x的反雙曲餘弦(inverse hyperbolic cosine)
Math.atanh(x) 返回x的反雙曲正切(inverse hyperbolic tangent)

5、 BigInt 數據類型

ES2020 引入了一種新的數據類型 BigInt(大整數),來解決這個問題,這是 ECMAScript 的第八種數據類型。BigInt 只用來表示整數,沒有位數的限制,任何位數的整數都可以精確表示。

1234 // 普通整數
1234n // BigInt

// BigInt 的運算
1n + 2n // 3n
typeof 123n // 'bigint'

BigInt(123) // 123n
BigInt('123') // 123n
BigInt(false) // 0n
BigInt(true) // 1n
Tags: