ES6學習3(各種類型的拓展)

字符串的拓展

字符的Unicode表示法

ES5中,Unicode必須是\uxxxx形式的,少與4位不行,多於四位必須拆成兩個4位的來表示。在ES6中,將一個碼點值放在大括號中可以自動解析。與雙字節表示等價。

console.log("\uD842\uDFB7");// "��"
console.log("\u20BB7");//亂碼
console.log("\u{20BB7}");//正常解析
console.log("\u41");//報錯
console.log("\u{41}");//A
console.log('\u{1F680}' === '\uD83D\uDE80');//true

codePointAt()

在JS內部,字符以UTF-16的格式儲存,每個字符固定爲兩個字節,對於那些需要4個字節來儲存的字符,JS認爲他們是兩個字符。此時charAt方法和charCodeAt方法都無法完整獲取這樣的字符的碼點值。
codePointAt可以

var s = '��b';

console.log(s.codePointAt(0).toString(16)); // 20bb7
console.log(s.codePointAt(2).toString(16)); // 62

可以看到,這個方法正確的獲取了碼點,雙字節和四字節的都可以。
不過注意到b應該是第2個字而我們傳進了2。因爲這個方法並不能判斷這個字符前面的所有字符是雙字節還是四字節的,所以只能按照雙字節的下標來。
這個問題是可以解決的。使用for…of循環,它可以正確識別4字節字符。

var s = '��a';
for (let ch of s) {
  console.log(ch.codePointAt(0).toString(16));
}

String.fromCodePoint()

String.fromCharCode的支持四字節版

String.fromCodePoint(0x20BB7)

字符串遍歷器接口

剛纔已經提到了,使用for…of可以正確識別4字節字符爲一個字符。

at()

這個是charAt的四字節版,目前貌似大多數都沒實現。

'��'.at(0) // "��"

normalize()

標準化Unicode
比如帶音標的字母,可以2字節表示也可以4字節表示,這個方法標準化它

'\u01D1'.normalize() === '\u004F\u030C'.normalize()

includes(), startsWith(), endsWith()

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

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

repeat

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

padStart(),padEnd()

ES7中推出了字符補全長度的功能,如果某個字符串不夠指定長度,就會在頭部或尾部補全。

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

位數超了會截掉用來補全的字符串

'abc'.padStart(10, '0123456789')// '0123456abc'

用於補全指定位數和提示字符串格式很方便

'123456'.padStart(10, '0') // "0000123456"
'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"

模板字符串

var x = 1;
var y = 2;

`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"

`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"

var obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// 3
function fn() {
  return "Hello World";
}

`foo ${fn()} bar`
// foo Hello World bar

實例:模板編譯

通過字符串模板生正式模板的實例

var template = `
<ul>
  <% for(var i=0; i < data.supplies.length; i++) { %>
    <li><%= data.supplies[i] %></li>
  <% } %>
</ul>
`;
function compile(template){
    var evalExpr = /<%=(.+?)%>/g;
    var expr = /<%([\s\S]+?)%>/g;

    template = template
        .replace(evalExpr, '`); \n  echo( $1 ); \n  echo(`')
        .replace(expr, '`); \n $1 \n  echo(`');

    template = 'echo(`' + template + '`);';

    var script =
        `(function parse(data){
    var output = "";

    function echo(html){
      output += html;
    }

    ${ template }

    return output;
  })`;

    return script;
}
var parse = eval(compile(template));
console.log(parse({ supplies: [ "broom", "mop", "cleaner" ] }));

這裏就是使用正則表達式將template模板轉換成了類似如下代碼並以字符串形式返回,然後使用eval方法把它變成可執行的。

echo('<ul>');
for(var i=0; i < data.supplies.length; i++) {
  echo('<li>');
  echo(data.supplies[i]);
  echo('</li>');
};
echo('</ul>');

標籤模板

這是函數調用的一種特殊形式,標籤指的就是函數,緊跟在後的模板字符串就是它的參數。第一個參數是被插入值分割成數組的字符串,後面就依次是插入值了。

var a = 5;
var b = 10;

function tag(s, v1, v2) {
    console.log(s[0]);
    console.log(s[1]);
    console.log(s[2]);
    console.log(v1);
    console.log(v2);

    return "OK";
}

tag`Hello ${ a + b } world ${ a * b}`;
//相當於tag(['Hello ', ' world ', ''], 15, 50)

這個可以用來過濾HTML字符串,以防用戶輸入惡意內容。

var message =
  SaferHTML`<p>${sender} has sent you a message.</p>`;

function SaferHTML(templateData) {
  var s = templateData[0];
  for (var i = 1; i < arguments.length; i++) {
    var arg = String(arguments[i]);

    // Escape special characters in the substitution.
    s += arg.replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;");

    // Don't escape special characters in the template.
    s += templateData[i];
  }
  return s;
}

進行多國語言轉換也很方便~

i18n`Welcome to ${siteName}, you are visitor number ${visitorNumber}!`
// "歡迎訪問xxx,您是第xxxx位訪問者!"

String.raw

這個方法充當模板字符串的處理函數,返回一個斜槓都被轉義,變量被替換的字符串。

String.raw`Hi\n${2+3}!`;
// "Hi\\n5!"

String.raw`Hi\u000A!`;
// 'Hi\\u000A!'

數值類型的拓展

二進制和八進制表示法

必須使用0b(或0B)和0o(或0O)表示
轉換爲十進制

Number('0b111')  // 7
Number('0o10')  // 8

Number.isFinite(), Number.isNaN()

它們與傳統的全局方法isFinite()和isNaN()的區別在於,傳統方法先調用Number()將非數值的值轉爲數值,再進行判斷,而這兩個新方法只對數值有效,非數值一律返回false。

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

Number.parseInt(), Number.parseFloat()

就是將全局方法移到了number對象上,這樣更合理。

Number.isInteger()

用來判斷一個數是否爲整數

Number.isInteger(25) // true
Number.isInteger(25.0) // true
Number.isInteger(25.1) // false

Number.EPSILON

新常量,非常小,因爲JS浮點預算存在誤差,如果這個誤差能夠小於這個常量,就可以認爲得到了正確的結果。

安全整數和Number.isSafeInteger()

JS中能夠準確表示的整數在-2^53到2^53之間,超過這個範圍就不行啦。
Number.MAX_SAFE_INTEGER和Number.MIN_SAFE_INTEGER值用來表示兩個上下限。
Number.isSafeInteger用來檢測一個整數在不在這個範圍中

Number.MAX_SAFE_INTEGER === Math.pow(2, 53) - 1// true
Number.MAX_SAFE_INTEGER === 9007199254740991// true
Number.isSafeInteger('a') // false
Number.isSafeInteger(null) // false
Number.isSafeInteger(NaN) // false
Number.isSafeInteger(Infinity) // false
Number.isSafeInteger(-Infinity) // false
Number.isSafeInteger(3) // true
Number.isSafeInteger(1.2) // false
Number.isSafeInteger(9007199254740990) // true
Number.isSafeInteger(9007199254740992) // false

指數運算

2 ** 2 // 4
a **= 2;
// 等同於 a = a * a;

Math對象的拓展

Math.trunc()

用於除去一個數的小數部分

Math.trunc(4.1) // 4
Math.trunc(4.9) // 4
Math.trunc(-4.1) // -4
Math.trunc('123.456')
// 123
Math.trunc(NaN);      // NaN
Math.trunc('foo');    // NaN
Math.trunc();         // NaN

Math.sign()

用來判斷一個數到底是正數負數還是0

Math.sign(-5) // -1
Math.sign(5) // +1
Math.sign(0) // +0
Math.sign(-0) // -0
Math.sign(NaN) // NaN
Math.sign('foo'); // NaN
Math.sign();      // NaN

Math.cbrt()
Math.clz32()
Math.imul()
Math.fround()
Math.hypot()
Math.expm1()
Math.log1p()
Math.log10()
Math.log2()
Math.sinh(x)
Math.cosh(x)
Math.tanh(x)
Math.asinh(x)
Math.acosh(x)
Math.atanh(x)

數組的拓展

Array.from()

這個方法用來將兩類對象轉換爲真正的數組,類似數組的對象,可遍歷的對象(有Iterator接口的)。

let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};

// ES5的寫法
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']

// ES6的寫法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']

let namesSet = new Set(['a', 'b'])
Array.from(namesSet) // ['a', 'b']

實際應用中,常見的就是NodeList集合和函數內部的arguments。
擴展運算符背後調用的是遍歷器接口(Symbol.iterator),如果一個對象沒有部署這個接口,就無法轉換。Array.from方法則是還支持類似數組的對象。所謂類似數組的對象,本質特徵只有一點,即必須有length屬性。因此,任何有length屬性的對象,都可以通過Array.from方法轉爲數組,而此時擴展運算符就無法轉換。

Array.from({ length: 3 });
// [ undefined, undefined, undefinded ]

Array.from還接收第二個參數,用來對每一個元素進行處理,就像map方法。

Array.from(arrayLike, x => x * x);
// 等同於
Array.from(arrayLike).map(x => x * x);

Array.from([1, 2, 3], (x) => x * x)

Array.from()的另一個應用是,將字符串轉爲數組,然後返回字符串的長度。因爲它能正確處理各種Unicode字符,可以避免JavaScript將大於\uFFFF的Unicode字符,算作兩個字符的bug。

function countSymbols(string) {
  return Array.from(string).length;
}

Array.of()

這個方法的存在是爲了彌補Array構造函數的不足。Array構造函數在參數不同的時候會有不同的表現

Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]

Array.of()的行爲超級統一

Array.of() // []
Array.of(undefined) // [undefined]
Array.of(1) // [1]
Array.of(1, 2) // [1, 2]

數組實例的copyWithin()

這個函數會把指定位置的成員複製到其他位置,目標位置的成員被覆蓋。
接收3個參數:

  • target(必需):從該位置開始替換數據。
  • start(可選):從該位置開始讀取數據,默認爲0。如果爲負值,表示倒數。
  • end(可選):到該位置前停止讀取數據,默認等於數組長度。如果爲負值,表示倒數。
[1, 2, 3, 4, 5].copyWithin(0, 3)
// [4, 5, 3, 4, 5]
// 將3號位複製到0號位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]

find()和findIndex()

[1, 5, 10, 15].find(function(value, index, arr) {
  return value > 9;
}) // 10
[1, 5, 10, 15].findIndex(function(value, index, arr) {
  return value > 9;
}) // 2

fill()

用給定的值填充數組,多傳兩個參數還可以規定填充的起始和結束位置。

['a', 'b', 'c'].fill(7)// [7, 7, 7]
new Array(3).fill(7)// [7, 7, 7]
['a', 'b', 'c'].fill(7, 1, 2)// ['a', 7, 'c']

entries(),keys()和values()

這三個方法用於遍歷數組,他們都返回一個遍歷器對象,可以用for…of循環進行遍歷

for (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1

for (let elem of ['a', 'b'].values()) {
  console.log(elem);
}
// 'a'
// 'b'

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"

includes()

數組是否包含所給元素,可選的傳入起始位置:

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, NaN].includes(NaN); // true
[1, 2, 3].includes(3, 3);  // false

這個方法比indexof要好,可以正確判斷NaN。使用起來也更直觀。

[NaN].indexOf(NaN)// -1
[NaN].includes(NaN)// true

數組的空位

ES5中各個數組方法對空位的處理非常不統一,有的跳過,有的視爲undefined。
在ES6新的這些方法中,統一處理爲undefined。
但是考慮到ES5中很不統一,儘量避免出現空位。

發佈了128 篇原創文章 · 獲贊 6 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章