前端小记6——项目中常用的ES6方法

现在很多功能用es5的方法也能实现功能,但es6提供的方法显得更为高效。记录下目前常用的几个方法。

1、字符包含

通过str.includes('a')来判断, 若str中包含a则结果为true,否则为false。

eg:

let str = 'abcd';

console.log(str.includes('a')); // true

console.log(str.includes('f')); // false

此外,支持第二个参数:

console.log(str.includes('d', 1)); // true  从索引号1开始搜索(包括1)

注意:includes()方法区分大小写。

2、字符首位判断

通过str.startsWidth('a')来判断, 若a为str的首字符则结果为true,否则为false。

eg:

let str = 'abcd';

console.log(str.startsWidth('a')); // true

console.log(str.startsWidth('b')); // false

此外,支持第二个参数:

console.log(str.startsWidth('cd', 2)); // true

3、字符末位判断

通过str.endsWith('a')来判断,若a为str的末位字符则结果为true,否则为false。

eg:

let str = 'abcd';

console.log(str.endsWith('d')); // trude

console.log(str.endsWith('b')); // false

此外,支持第二个参数:

console.log(str.endsWith('ab', 2)); // true 参数代表前2个(不包括第2)

4.两个值判断是否相等

传统es5判断相等用“==”(会自动转换数据类型)或“===”(有限制,比如NaN,+0,-0)

es6方法:Object.is

eg:Object.is('a', 'a'); // true

        Object.is({}, {}); // false

对比:

+0 === -0 // true

NaN === NaN // false

Object.is(+0, -0) // false

Object.is(NaN, NaN) true

5、数组中查找第一个满足元素(包含)

方法:some()方法会依次执行,当遇到满足条件的返回true,跳出循环。若无满足项,返回false。

Ps:该方法不会改变原始数组,且对空数组不生效。

eg: 

var a = [1,3,5,6];

function f () {

  return b = 5;

}

console.log(a.some(f)); // true

6、模板字符串(也可用于字符拼接)

传统:

$('#id').append(

   'This is <b>' + page.no + '</b>' + 

    'item in your page' + '<em>' + page.name +

   '</em> in it.'

);

es6:

$('#id).append(

  This is <b>${page.no}</b> item in your page <em>${page.name}</em> in it.

);

注意:在模板中需要使用反引号,需在前面用反斜杠转译。且模板中的空格和换行都会保留。

大括号中可以是变量或函数方法或者嵌套。

7、数组遍历

方法for of

eg: 

var a = ['m', 'n', 'o'];

for (i of a) {

  console.log(i); // 输出的是值 m, n, o

}

8、数组去重

eg:

var a = new Set("Hello word");

for (var b of a) {

   console.log(b+" ")

}

// H e l o w r d 

方法一:

function fn(arr) {

  return Array.form(new Set(arr)) // Array.from方法可以将 Set 结构转为数组

}

const items = [1,2,3,4,5,6,7,1,2,1,3,1,2,3];

console.log(fn(items)) // [1,2,3,4,5,6,7]

方法二:

let arr1 = [12,13,23,45,46,48,78,79,45,12,13,23];

let arr = new Set(arr1)

console.log([...arr]) // [ 12, 13, 23, 45, 46, 48, 78, 79 ]

9、常用的并集、交集、差集

eg:

let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
// 并集
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}
// 交集
let intersect = new Set([...a].filter(x => b.has(x)));
// set {2, 3}
// 差集
let difference = new Set([...a].filter(x => !b.has(x)));
// Set {1}
 
未完,待添加。

 

猜你喜欢

转载自www.cnblogs.com/bookchilds/p/9342505.html