ES6經常使用但被忽略的方法(第一彈)

解構賦值

剔除對象不須要的屬性的值

const obj = {
    name: 'detanx',
    age: 24,
    height: 180
}
// 剔除height
const { height, ...otherObj } = obj;
// otherObj => {name: 'detanx', age: 24}
複製代碼

剔除數組不須要的項

const arr = ['detanx', 24, 180]
// 剔除 第一項
const [ name, ...otherArr ] = arr;
// otherArr => [24, 180]
複製代碼

設置默認值

  • ES6 內部使用嚴格相等運算符(===),判斷一個位置是否有值。因此,只有當一個數組成員嚴格等於undefined,默認值纔會生效。(面試可能會遇到)
const [x = 1] = [undefined];
// x 1
const [x = 1] = [null];
// x null
複製代碼
  • 能夠引用解構賦值的其餘變量,但該變量必須已經聲明。
let [x = 1, y = x] = [];     // x=1; y=1
let [x = 1, y = x] = [2];    // x=2; y=2
let [x = 1, y = x] = [1, 2]; // x=1; y=2
let [x = y, y = 1] = [];     // ReferenceError: y is not defined
複製代碼

不須要額外變量就可交換兩個變量的值

let x = 1, y = 2;
[x, y] = [y, x]
// x: 2,y: 1
複製代碼

獲取指定的值

// 返回一個數組
function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();

// 返回一個對象
function example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();
// 導入模塊某些方法
import { clone } from '_lodash';
複製代碼

字符串

includes

  • 以前判斷目標字符或字符串片斷是否存在某個字符串中須要使用indexOf來判斷,返回的結果是首次出現目標的位置,不存在返回-1。實際場景咱們並不須要回去目標在字符串中的位置,只須要判斷目標是否該字符串中便可,因此咱們可使用includes。同時能夠接收第二個參數,表示從左到右第幾個位置開始
'detanx'.includes('tan') // true
'detanx'.includes('tan',3) // false
複製代碼

查詢目標字符在字符串開始或結尾

  • str.startsWith(char[, pos])查詢char是不是字符串開頭,pos表明從左到右哪個位置算起始位置。
'detanx'.startsWith('tan', 2) // true
複製代碼
  • str.endsWith(char[, len])查詢char是不是字符串,len表明從左到右包含多少個字符(即長度)。
'detanx'.endsWith('tan', 5) // true
複製代碼

字符串重複多少次repeat

  • 重複字符串多少次,接收一個參數
    1. 當參數爲大於-1而且小於1或者爲NaN時做爲0
    2. 大於1且爲小數時向下取整
    3. 爲infinity或者小於-1時會報錯
    4. 其餘類型會轉爲數字
'detanx'.repeat(0) // ""
'detanx'.repeat(-0.7) // ""
'detanx'.repeat(NaN) // ""
'detanx'.repeat(2) // "detanxdetanx"
'detanx'.repeat({}) // ""
'detanx'.repeat([]) // ""
'detanx'.repeat(()=>{}) // ""
複製代碼

字符串補全

  • 從左邊補全padStart,當字符串長度不夠須要指定以什麼開頭,不傳第二參數默認使用空格。
// 時間顯示小於10補0
const x = 7
if(x < 10) String(x).padStart(2,'0')
// 替換結尾
'04'.padStart(10, 'YYYY-MM-DD'); // 'YYYY-MM-04'
複製代碼
  • 從右邊補全padEnd,當字符串長度不夠須要指定以什麼結尾,不傳第二參數默認使用空格。
'de'.padEnd(6, 'tanx'); // detanx
複製代碼

去掉頭或尾空格

  • 除了空格鍵,這兩個方法對字符串頭部(或尾部)的 tab 鍵、換行符等不可見的空白符號也有效。
  • 瀏覽器還部署了額外的兩個方法,trimLeft()trimStart()的別名,trimRight()trimEnd()的別名。
// 去掉頭部空格
' detanx '.trimStart(); // 'detanx '
' detanx '.trimLeft(); // 'detanx '
// 去掉尾部空格
' detanx '.trimEnd(); // ' detanx'
' detanx '.trimRight(); // ' detanx'
複製代碼

數值擴展

isFinite

  • 用來檢查一個數值是否爲有限的(finite),即不是Infinity或者-Infinity。其餘類型直接返回false,包括NaN
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
複製代碼

isInteger

  • 判斷一個數值是否爲整數。若是對數據精度的要求較高,不建議使用Number.isInteger()判斷一個數值是否爲整數。
  • JavaScript 採用 IEEE 754 標準,數值存儲爲64位雙精度格式,數值精度最多能夠達到 53 個二進制位(1 個隱藏位與 52 個有效位)。若是數值的精度超過這個限度,第54位及後面的位就會被丟棄,這種狀況下,Number.isInteger可能會誤判。
Number.isInteger(3.0000000000000002) // true
複製代碼
  • 這個小數的精度達到了小數點後16個十進制位,轉成二進制位超過了53個二進制位,致使最後的那個2被丟棄。
  • 若是一個數值的絕對值小於Number.MIN_VALUE(5E-324),即小於 JavaScript 可以分辨的最小值,會被自動轉爲 0Number.isInteger也會誤判。
Number.isInteger(5E-324) // false
Number.isInteger(5E-325) // true
複製代碼

isSafeInteger

  • Number.isSafeInteger()是用來判斷一個整數是否落在Number.MAX_SAFE_INTEGERNumber.MIN_SAFE_INTEGER這兩個常量範圍以內。
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

Number.isSafeInteger(Number.MIN_SAFE_INTEGER - 1) // false
Number.isSafeInteger(Number.MIN_SAFE_INTEGER) // true
Number.isSafeInteger(Number.MAX_SAFE_INTEGER) // true
Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1) // false
複製代碼
  • 實際使用這個函數時,須要注意。驗證運算結果是否落在安全整數的範圍內,不要只驗證運算結果,而要同時驗證參與運算的每一個值。

Math.trunc

  • Math.trunc方法用於去除一個數的小數部分,返回整數部分。非數值,Math.trunc內部使用Number方法將其先轉爲數值。空值和沒法截取整數的值,返回NaN
Math.trunc(4.9) // 4
Math.trunc(-4.1) // -4
Math.trunc(-0.1234) // -0

Math.trunc('123.456') // 123
Math.trunc(true) //1
Math.trunc(false) // 0
Math.trunc(null) // 0

Math.trunc(NaN);      // NaN
Math.trunc('foo');    // NaN
Math.trunc();         // NaN
Math.trunc(undefined) // NaN
複製代碼
  • 模擬實現
Math.trunc = Math.trunc || function(x) {
  return x < 0 ? Math.ceil(x) : Math.floor(x);
};
複製代碼

Math.sign

  • Math.sign方法用來判斷一個數究竟是正數、負數、仍是零。對於非數值,會先將其轉換爲數值。
    1. 參數爲正數,返回+1;
    2. 參數爲負數,返回-1;
    3. 參數爲 0,返回0;
    4. 參數爲-0,返回-0;
    5. 其餘值,返回NaN。
Math.sign(-5) // -1
Math.sign(5) // +1
Math.sign(0) // +0
Math.sign(-0) // -0
Math.sign(NaN) // NaN
複製代碼
  • 若是參數是非數值,會自動轉爲數值。對於那些沒法轉爲數值的值,會返回NaN
Math.sign('')  // 0
Math.sign(true)  // +1
Math.sign(false)  // 0
Math.sign(null)  // 0
Math.sign('9')  // +1
Math.sign('foo')  // NaN
Math.sign()  // NaN
Math.sign(undefined)  // NaN
複製代碼
  • 模擬實現
Math.sign = Math.sign || function(x) {
  x = +x; // convert to a number
  if (x === 0 || isNaN(x)) {
    return x;
  }
  return x > 0 ? 1 : -1;
};
複製代碼

Math.cbrt

  • Math.cbrt()方法用於計算一個數的立方根。
Math.cbrt(-1) // -1
Math.cbrt(0)  // 0
Math.cbrt(1)  // 1
Math.cbrt(2)  // 1.2599210498948732
複製代碼
  • 對於非數值,Math.cbrt()方法內部也是先使用Number()方法將其轉爲數值。
Math.cbrt('8') // 2
Math.cbrt('hello') // NaN
複製代碼
  • 模擬實現
Math.cbrt = Math.cbrt || function(x) {
  var y = Math.pow(Math.abs(x), 1/3);
  return x < 0 ? -y : y;
};
複製代碼

Math.hypot

  • Math.hypot方法返回全部參數的平方和的平方根。
Math.hypot(3, 4);        // 5
Math.hypot(3, 4, 5);     // 7.0710678118654755
Math.hypot();            // 0
Math.hypot(NaN);         // NaN
Math.hypot(3, 4, 'foo'); // NaN
Math.hypot(3, 4, '5');   // 7.0710678118654755
Math.hypot(-3);          // 3
複製代碼
  • 上面代碼中,3 的平方加上 4 的平方,等於 5 的平方。
  • 若是參數不是數值,Math.hypot方法會將其轉爲數值。只要有一個參數沒法轉爲數值,就會返回 NaN
相關文章
相關標籤/搜索