1. 程式人生 > >ECMAScript 6 學習系列課程 (ES6 常用內建方法的使用)

ECMAScript 6 學習系列課程 (ES6 常用內建方法的使用)

這裡寫圖片描述

在編寫Javascript的過程,我們經常會用到陣列過濾,字串等相關操作,比如會用到filter等方法,在ES6中同樣新增了很多內建方法,下面我們來了解一下。

Finding

[ 1, 3, 4, 2 ].find(x => x > 3) // 4

ES5實現例項:

[ 1, 3, 4, 2 ].filter(function (x) { return x > 3; })[0]; // 4

String Repeating

"foo".repeat(3)   //foofoofoo

String Searching

"hello".startsWith("ello"
, 1) // true "hello".endsWith("hell", 4) // true "hello".includes("ell") // true "hello".includes("ell", 1) // true "hello".includes("ell", 2) // false

類似語法大家一定用過:

"hello".indexOf("ello") === 1;    // true
"hello".indexOf("hell") === (4 - "hell".length); // true
"hello".indexOf("ell") !== -1;    //
true "hello".indexOf("ell", 1) !== -1; // true "hello".indexOf("ell", 2) !== -1; // false

Number Truncation

console.log(Math.trunc(42.7)) // 42
console.log(Math.trunc( 0.1)) // 0
console.log(Math.trunc(-0.1)) // -0

類似於:

function mathTrunc (x) {
    return (x < 0 ? Math.ceil(x) : Math.floor(x));
}
console.log(mathTrunc(42.7
)) // 42 console.log(mathTrunc( 0.1)) // 0 console.log(mathTrunc(-0.1)) // -0

判斷Number的sign(正負數):

console.log(Math.sign(7))   // 1
console.log(Math.sign(0))   // 0
console.log(Math.sign(-0))  // -0
console.log(Math.sign(-7))  // -1
console.log(Math.sign(NaN)) // NaN

以上就幾個內建函式的簡單用法,還有很多,會繼續跟進。