您的位置:首页 > Web前端 > JavaScript

ECMAScript 6 学习系列课程 (ES6 常用内置方法的使用)

2016-07-12 13:57 609 查看


在编写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


以上就几个内置函数的简单用法,还有很多,会继续跟进。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript