ES6 知识拓展

1.冻结对象

Object.freeze(obj)

方法可以冻结一个对象,冻结指的是不能向这个对象添加新的属性,不能修改其已有属性的值,不能删除已有属性,以及不能修改该对象已有属性的可枚举性、可配置性、可写性。也就是说,这个对象永远是不可变的。该方法返回被冻结的对象。

冻结的必须是对象

注:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

a.浅冻结&&深冻结

2.CommonJS 的写法和ES6 模块的写法

CommonJS: var XXX = require('xxx.xxx');

ES6:improt xxx from 'xxx';

3.function*

  定义:function* 这种声明方式(function关键字后跟一个星号)会定义一个生成器函数 (generator function),它返回一个  Generator  对象。(yield配合使用);

  示例:

function* generator(i) {
  yield i;
  yield i + 10;
}

var gen = generator(10);

console.log(gen.next().value);
// expected output: 10

console.log(gen.next().value);
// expected output: 20

console.log(gen.next().value);
// expected output: undefined

4.数组的本质是特殊的对象

 5....扩展运算符

function test(x,...y){console.log(x,y)};
test(1,2,3,4);//1,[2,3,4]

 6.RegExp对象

RegExp 对象表示正则表达式,它是对字符串执行模式匹配的强大工具.

a.直接量语法

/pattern/attributes

b.创建RegExp对象的语法:

new RegExp(pattern, attributes);

参数

参数 pattern 是一个字符串,指定了正则表达式的模式或其他正则表达式。

参数 attributes 是一个可选的字符串,包含属性 "g"、"i" 和 "m",分别用于指定全局匹配、区分大小写的匹配和多行匹配。ECMAScript 标准化之前,不支持 m 属性。如果 pattern 是正则表达式,而不是字符串,则必须省略该参数。

7.sort()

sort() 方法用于对数组的元素进行排序。

var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1"

arr.sort()//1,10,1000,25,40,5

如果要实现顺序排序需要传入一个函数;

function f(a,b){
  return a-b  
};

arr.sort(f)

 8.数组实例的 copyWithin()

数组实例的copyWithin方法,在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。也就是说,使用这个方法,会修改当前数组。

Array.prototype.copyWithin(target, start = 0, end = this.length)

这三个参数都应该是数值,如果不是,会自动转为数值。

// 将3号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]

// -2相当于3号位,-1相当于4号位
[1, 2, 3, 4, 5].copyWithin(0, -2, -1)
// [4, 2, 3, 4, 5]

// 将3号位复制到0号位
[].copyWithin.call({length: 5, 3: 1}, 0, 3)
// {0: 1, 3: 1, length: 5}

// 将2号位到数组结束,复制到0号位
let i32a = new Int32Array([1, 2, 3, 4, 5]);
i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5]

 8.数组去重

// 去除数组的重复成员
[...new Set(array)]
9.数组的循环
for...in循环读取键名,for...of循环读取键值。如果要通过for...of循环,获取数组的索引,可以借助数组实例的entries方法和keys方法
 
原文地址:https://www.cnblogs.com/nailc/p/9207362.html