4702 字
24 分钟
ES6新语法

目录#

参考文章:

查看对es6语法的支持#

D:\desktop\Vue> npm install -g es-checker
added 13 packages in 4s
PS D:\desktop\Vue> es-checker
ECMAScript 6 Feature Detection (v1.4.2)
Variables
√ let and const
√ TDZ error for too-early access of let or const declarations
√ Redefinition of const declarations not allowed
√ destructuring assignments/declarations for arrays and objects
√ ... operator
Data Types
√ For...of loop
√ Map, Set, WeakMap, WeakSet
√ Symbol
√ Symbols cannot be implicitly coerced
Number
√ Octal (e.g. 0o1 ) and binary (e.g. 0b10 ) literal forms
√ Old octal literal invalid now (e.g. 01 )
√ Static functions added to Math (e.g. Math.hypot(), Math.acosh(), Math.imul() )
√ Static functions added to Number (Number.isNaN(), Number.isInteger() )
String
√ Methods added to String.prototype (String.prototype.includes(), String.prototype.repeat() )
√ Unicode code-point escape form in string literals (e.g. \u{20BB7} )
√ Unicode code-point escape form in identifier names (e.g. var \u{20BB7} = 42; )
√ Unicode code-point escape form in regular expressions (e.g. var regexp = /\u{20BB7}/u; )
√ y flag for sticky regular expressions (e.g. /b/y )
√ Template String Literals
Function
√ arrow function
√ default function parameter values
√ destructuring for function parameters
√ Inferences for function name property for anonymous functions
× Tail-call optimization for function calls and recursion
Array
√ Methods added to Array.prototype ([].fill(), [].find(), [].findIndex(), [].entries(), [].keys(), [].values() )
√ Static functions added to Array (Array.from(), Array.of() )
√ TypedArrays like Uint8Array, ArrayBuffer, Int8Array(), Int32Array(), Float64Array()
√ Some Array methods (e.g. Int8Array.prototype.slice(), Int8Array.prototype.join(), Int8Array.prototype.forEach() ) added to the TypedArray prototypes
√ Some Array statics (e.g. Uint32Array.from(), Uint32Array.of() ) added to the TypedArray constructors
Object
√ __proto__ in object literal definition sets [[Prototype]] link
√ Static functions added to Object (Object.getOwnPropertySymbols(), Object.assign() )
√ Object Literal Computed Property
√ Object Literal Property Shorthands
√ Proxies
√ Reflect
Generator and Promise
√ Generator function
√ Promises
Class
√ Class
√ super allowed in object methods
√ class ABC extends Array { .. }
Module
× Module export command
× Module import command
=========================================
Passes 39 feature Detections
Your runtime supports 92% of ECMAScript 6
=========================================

基础语法#

var,let,const#

在能实现相同的功能情况下, 使用优先级: const > let > var

const str1 = "const定义";
// const定义常量, 不可改变 Assignment to constant variable.
// str1 = "change";
console.log(str1);
// 但是常量定义的对象中的
const obj = {
name: "Tiam",
age: 18
}
obj.name = "字节跳动";
obj.age = 9;
console.log(obj); // { name: '字节跳动', age: 9 }

模板字符串 | 字符串遍历#

// ES6 模板字符串语法
let str = "妖怪";
console.log(`${str}看打`);
// 遍历字符串
let string = "abcdefghijklmnopqrstuvwxyz";
// 打印0~25
for (const c in string) {
console.log(c);
}
// 打印a~z
for (const c of string) {
console.log(c);
}
// 解构赋值
const str2 = "PUA";
let [a, b, c] = str2;
console.log(a, b, c);
console.log(str2[1]);
// 字符串方法
// 判断是否包含某个字符
console.log(str2.includes("A"));
// 重复拼接自身
console.log(str2.repeat(2));

set, map, object#

// 对象
let obj_name, obj_age;
let obj1 = {
obj_name,
obj_age,
obj_func() {
console.log(this.obj_name);
}
}
obj1.obj_name = "对象名"
obj1.obj_func();
// Set结构, 不存储重复值
let set = new Set();
set.add("one");
set.add("two");
set.add("one");
console.log(set); // Set(2) { 'one', 'two' }
set.forEach(i => console.log(i))
// Map结构
let map = new Map();
map.set("邓紫棋", "《多远都要在一起》").set("周杰伦", "《明明就》");
console.log(map);

rest参数 | 函数参数默认值 | 箭头函数 | 扩展运算符#

arguments对象#

// 定义函数参数带默认值
function fun(name = "Tiam", age = 18) {
console.log(`${name}, ${age}`);
}
fun();
fun("字节", 102);
// 箭头函数 | 接收不定数的参数
let fun1 = (...songs) => console.log(songs);
fun1("泡沫", "再见", "A.N.I.Y", "光年之外");
// 函数体内可以通过arguments对
// 象来接收传递进来的参数。 arguments对象的length属性可以得到参数的数量。
function fun2(){
console.log(arguments); // [Arguments] { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }
console.log(arguments.length);
console.log(...arguments); // 1 2 3 4 5
}
fun2(1,2,3,4,5);
// 扩展运算符 => 可迭代对象包括常用的集合对象(数组、Set、Map集合)和字符串都是可迭代对象. => 展开数组
let obj = {
"壹": 1,
"贰": 2,
"叁": 3
}
console.log({...obj}); // { '壹': 1, '贰': 2, '叁': 3 }

Class类#

class Person {
// 无构造方法时, 自动创建一个无参构造方法
constructor(name, age) {
this.name = name;
this.age = age;
}
getName() {
return this.name;
}
getAge() {
return this.age;
}
setName(name) {
this.name = name;
}
setAge(age) {
this.age = age;
}
toString() {
return this.name + '(' + this.age + ')';
}
run() {
console.log(`Just run!${this.name}`);
}
static cry() {
console.log("so sad, so cry!");
}
}
// 类的本质就是 函数
console.log(typeof Person); // function
Person.cry();
let scientist = new Person("爱因斯坦", 77);
console.log(scientist);
console.log(scientist.toString());
let mathematician = new Person();
mathematician.setName("Oula");
mathematician.setAge(98);
console.log(mathematician.getName());
console.log(mathematician.getAge());
// 类的继承
class Student extends Person {
constructor(name, age, college) {
super(name, age);
this.college = college;
}
getCollege() { return this.college }
}
let linux_father = new Student("林纳斯", 21, "芬兰大学");
console.log(linux_father.getCollege); // [Function: getCollege]
console.log(linux_father.getCollege()); // 芬兰大学
console.log(linux_father); // Student { name: '林纳斯', age: 21, college: '芬兰大学' }
Student.cry();

let、const、var 的区别#

  • var:使用 var 声明的变量,其作用域为该语句所在的函数内,且存在变量提升现象
  • let:使用 let 声明的变量,其作用域为该语句所在的代码块内,不存在变量提升。
  • const:使用 const 声明的是常量,在后面出现的代码中不能再修改该常量的值。
varletconst
函数级作用域块级作用域块级作用域
变量提升不存在变量提升不存在变量提升
值可以改变值可以改变值不可以改变

1.关于let#

let arr = [];
for (let i = 0; i < 2; i++) {
arr[i] = function () {
console.log(i);
}
}
arr[0]();
arr[1]();

2.关于const#

//常量赋值后,值不能修改。
const PI = 3.14;
PI = 100; // 报错Assignment to constant variable.
const ary = [100, 200];
ary[0] = 'a';
ary[1] = 'b';
console.log(ary); // ['a', 'b'];
ary = ['a', 'b']; // 报错Assignment to constant variable.

3.关于var#

var关键字声明的变量,无论实际声明的位置在哪,都会被视为声明在函数的顶部、如果声明不在任意函数内,则视为在全局作用域的顶部

ES模块导入规则#

*容易出错的地方*

  1. 页面不基于服务器运行,会出现跨域的错误 origin ‘null’ has been blocked by CORS policy: Cross origin requests are only
  2. 使用模块化时,页面不加type = “module” 会出现语法错误 app.js:1 Uncaught SyntaxError: Unexpected token {
<script src="./module/app.js" type="module"></script>
  1. import导入模块时不添加 .js 的后缀名会报找不到module错误 GET xxx net::ERR_ABORTED 404 (Not Found)
import { Student } from './Student.js';

导入导出方式

  1. 导出方式
  • 定义时导出
  • 批量导出
  • 导出重命名(不建议)
  • 默认导出
// 1.定义时导出
export let uname = '李四';
export function showStudentName(){
console.log(uname);
}
export class SomeAnimalInfo{
constructor(type,age){
this.type = type;
this.age = age;
}
showInfo(){
console.log(`物种:${this.type},年龄:${this.age}`);
}
}
// 2.批量导出
const PI = 3.1415926;
const DBNAME = 'Local';
... ...
export { PI, DBNAME };
// 3.默认导出 - 工具类
export default class {
static log(msg) {
let now = new Date();
console.log(`${now.toLocaleString()} ${msg}`);
}
static setCookie(){
}
... ...
}

导入方式

  • 导入重命名
  • 导入整个模块
  • 导入默认模块
//1.导入重命名 as语法
import {num, showStudentName as showName} from './all.js';
// 2.导入整个模块 需要使用as重命名,接收的是一个对象
import * as cons from './const.js';
// 3.导入默认模块 需要起名,名字包含导出内容
import Tool from './tools.js';

Symbol#

ES6引入了一种新的原始数据类型Symbol,表示独一无二的值。它是JavaScript语言的第七种数据类型,前六种是:Undefined、Null、布尔值(Boolean)、字符串(String)、数值(Number)、对象(Object)

  • Symbol
  • null
  • undefined
  • boolean
  • string
  • number
  • object
let str1 = "邓紫棋";
let str2 = "邓紫棋";
console.log(str1); // 邓紫棋
console.log(typeof str1); //string
console.log(str1 == str2); // true
let str3 = Symbol("邓紫棋");
let str4 = Symbol("邓紫棋");
console.log(str3); //Symbol(邓紫棋)
console.log(typeof str3); //symbol
console.log(str3 == str4); // false

Promise对象#

  • Promise是异步编程的一种解决方案
  • 简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果。
  • 从语法上说,Promise是一个对象,从它可以获取异步操作的消息。
  • Promise提供统一的API,各种异步操作都可以用同样的方法进行处理。
  • ES6规定,Promise对象是一个构造函数,用来生成Promise实例。
  • http://caibaojian.com/es6/promise.html

进制表示#

// 二进制
console.log(0B101 == 5); // true
// 八进制
console.log(0O777); // 511

Array.from#

  • 只要是部署了Iterator接口的数据结构,Array.from都能将其转为数组
  • 类似数组的对象(array-like object)和可遍历(iterable)的对象(包括ES6新增的数据结构Set和Map)
Array.from
let map = new Map();
map.set("邓紫棋", "《多远都要在一起》").set("周杰伦", "《明明就》");
let arr1 = Array.from(map);
console.log(arr1);
let set = new Set();
set.add("one").add("two").add("three");
let arr2 = Array.from(set);
console.log(arr2);
const arrayLike = {
0: "Tiam",
1: 18,
2: "hbnu",
length: 3
}
let arr3 = Array.from(arrayLike);
console.log(arr3);
// Array.of 方法用于将一组值,转换为数组。
// 只有当参数个数不少于2个时,Array()才会返回由参数组成的新数组。参数个数只有一个时,实际上是指定数组的长度
let arr4 = Array.of(1, "2", '3', true, set, map);
console.log(arr4);
// 函数的name属性
let fun = function () { }
console.log(fun.name);

严格模式#

  • ES6 => 只要函数参数使用了默认值、解构赋值、或者扩展运算符,那么函数内部就不能显式设定为严格模式
function doSomething(a, b) {
// 声明为严格模式
'use strict';
// code
}

箭头函数#

箭头函数有几个使用注意点。

(1)函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。

(2)不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。

(3)不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用Rest参数代替。

(4)不可以使用yield命令,因此箭头函数不能用作Generator函数。

上面四点中,第一点尤其值得注意。*this*对象的指向是可变的,但是在箭头函数中,它是固定的。

// 箭头函数
// 一个参数时, 不需要写括号; 函数体只有一条语句时, 且为返回语句时, 可省大括号
let pow2 = param => param * param;
console.log(pow2(9));
// 无参
let fun1 = () => {
console.log("操作系统");
console.log("数据结构");
}
fun1();
// 多个参数
let fun2 = (song1,song2)=>{
console.log(`${song1}很好听`);
return song2;
}
console.log(fun2("where are you", "kiss the rain"));

Generator 函数#

  • Generator函数是分段执行的,yield语句是暂停执行的标记,而next方法可以恢复执行。
  • Generator函数是一个状态机,封装了多个内部状态。
  • 执行Generator函数会返回一个遍历器对象,也就是说,Generator函数除了状态机,还是一个遍历器对象生成函数
  • function关键字与函数名之间有一个星号;
  • 函数体内部使用yield语句,定义不同的内部状态

JS#

关系运算符#

运算符解释
==自动转换数据类型后比较
!=
===不进行数据类型转换, 直接比较(推荐)
!==

比较规则

  • 1.两个操作数都是数值,则数值比较;
  • 2.两个操作数都是字符串,则比较两个字符串对应的字符编码值;
  • 3.两个操作数有一个是数值,则将另一个转换为数值,再进行数值比较;
  • 4.两个操作数有一个是对象,则先调用valueOf()方法或toString()方法,再用结果比较;

类型#

typeof 可以输出的类型有以下7种类型

  • undefined
  • boolean
  • string
  • number
  • object
  • function
  • symbol
> typeof true
'boolean'
> typeof 1
'number'
> typeof {}
'object'
> typeof Symbol()
'symbol'
> typeof Symbol
'function'
> typeof "hello"
'string'
> typeof x
'undefined'
> typeof null
'object'

数据类型#

基本数据类型

  • boolean
  • string
  • number
  • null
  • undefned

复杂数据类型

  • Object
  • Array
  • Set
  • Map
  • symbol

布尔类型的隐私转换 | 任何值都可转换为Boolean值#

类型值为true值为false
booleantruefalse
string非空字符串空字符串
object任意对象null
number非00和NaN
undefinedundefined
// 5个特殊的false值
> Boolean("")
false
> Boolean(null)
false
> Boolean(0)
false
> Boolean(NaN)
false
> Boolean(undefined)
false

非数值 运算 转换#

> parseInt(true)
NaN
> parseInt("123")
123
> parseInt("abc123")
NaN
> true+2
3
> false+2
2
> "abc"+1
'abc1'
> null+1
1
> undefined+1
NaN
> Symbol()+1
Uncaught TypeError: Cannot convert a Symbol value to a number
> {a: 2}+2
'[object Object]2'

Array#

// Array类型
// 把一个元素或一组元素(数组)添加到当前数组的末尾。
let arr = [1,2,3];
arr.push(4,5);
console.log(arr);
// [ 1, 2, 3, 4, 5 ]
// 把两个数组或元素组合在一起,但是不会改变调用者的结构。
let arr1 = arr.concat([6,7]);
console.log(arr1);
/*
[
1, 2, 3, 4,
5, 6, 7
]
*/
// 删除数组中最后一个元素,并返回删除的元素。
arr1.pop();
console.log(arr1);
// [ 1, 2, 3, 4, 5, 6 ]
// 删除指定元素, 返回值是被删除掉的那部分数组
let arr2 = arr1.splice(1,2); // 删除从下标1开始的2个元素, 并返回
console.log(arr2);
// [ 2, 3 ]
// 反转数组
console.log(arr1.reverse());
// [ 6, 5, 4, 1 ]
// 返回一个字符串,字符串的内容是数组的所有元素,元素之间通过指定的分隔符进行分隔。
console.log(arr1.join("+"));
// 6+5+4+1

Date | Math | 编码 | 构造对象#

// 返回一个从1970年1月1日0时开始到调用这个方法的此时此刻经过的毫秒数。
let beginTime = Date.now();
let sum = 0;
for (let i = 0; i < 10000; i++) {
sum += i;
}
console.log(sum);
console.log("计算1到10000之和, 用时多少毫秒? " + (Date.now() - beginTime));
console.log(new Date().toISOString());
// 2022-11-24T01:28:31.352Z
// URL 编码
console.log(encodeURIComponent("微信$")); // %E5%BE%AE%E4%BF%A1%24
// 解码
console.log(decodeURIComponent("%E5%BE%AE%E4%BF%A1%24")); // 微信$
// 解析字符串为代码 eval
let str = "console.log(10086);";
eval(str); // 10086
// Math对象
console.log(Math.E); // 2.718281828459045
// Math.ceil()执行向上舍入,即它总是将数值向上舍入为最接近的整数;
// Math.floor()执行向下舍入,即它总是将数值向下舍入为最接近的整数;
// Math.round()执行标准舍入,即它总是将数值四舍五入为最接近的整数;
console.log(Math.random()); // 返回介于0到1之间一个随机数,不包括0和1
// 工厂模式 创建对象
function createObject(name, age) {
//集中实例化的函数
var obj = new Object();
obj.name = name;
obj.age = age;
obj.run = function () {
return this.name + this.age + "运行中...";
};
return obj;
}
var box1 = createObject("Lee", 100); //第一个实例
var box2 = createObject("Jack", 200); //第二个实例
alert(box1.run());
alert(box2.run()); //保持独立
// 改进 => 构造函数创建
function Box(name, age) {
//构造函数模式
this.name = name;
this.age = age;
this.run = function () {
return this.name + this.age + "运行中...";
};
}
var box1 = new Box("Lee", 100); //new Box()即可
var box2 = new Box("Jack", 200);
alert(box1.run());
alert(box1 instanceof Box); //很清晰的识别他从属于Box

事件#

UI事件#

  • load, 当页面完全加载完之后(包括所有的图像、js文件、css文件等外部资) 就会触发window上面的load事件。
  • unload, unload事件与load事件相对的。在文档被完全卸载后触发
  • abort,
  • error,
  • select,
  • resize, 当调整浏览器的窗口到一个新的宽度或高度时,就会触发
  • scroll scroll事件会在文档被滚动期间重复被触发

焦点事件#

  • blur 、blur事件在元素失去焦点时触发。
  • focus、focus事件在元素获得焦点时触发。
  • focusin、focusin() 方法在任意子元素获得焦点时也会触发
  • focusout focusout() 方法在任意子元素失去焦点时也会触发。

鼠标事件#

  • click 单击
  • dbclick 双击
  • mousedown 在用户按下了任意鼠标按钮时触发。
  • mouseenter 在鼠标光标从元素外部首次移动到元素范围内时触发
  • mouseleave 元素上方的光标移动到元素范围之外时触发。
  • mousemove 光标在元素的内部不断的移动时触发。
  • mouseover 鼠标指针位于一个元素外部,然后用户将首次移动到另一个元素边界之内时触发。
  • mouseout 用户将光标从一个元素上方移动到另一个元素时触发。
  • mouseup 在用户释放鼠标按钮时触发。
  • mousewheel 通过鼠标滚轮在垂直方向上滚动页面时

键盘事件#

  • keydown 事件会在用户按下一个键盘按键时发生;按住不放,会重复触发
  • kypress事件会在用户按下键盘上的字符键时触发,按住不放,会重复触发。
  • keyup事件会在用户释放键盘上的按键时触发

事件对象的常用属性和方法#

  • event.currentTarget属性:返回事件当前所在的节点,即正在执行的监听函数所绑定的那个节点
  • event.target属性:返回原始触发事件的那个节点,即事件最初发生的节点。
  • event.type属性返回一个字符串,表示事件类型。该属性只读。
  • event.eventPhase属性返回一个整数常量,表示事件目前所处的阶段。该属性只读。
  • 0:事件目前没有发生。 1:事件目前处于捕获阶段,即处于从祖先节点向目标节点的传播过程中。 2:事件到达目标节点,即event.target属性指向的那个节点。 3:事件处于冒泡阶段,即处于从目标节点向祖先节点的反向传播过程中
  • event.cancelable属性返回一个布尔值,表示事件是否可以取消。
  • event.preventDefault方法取消浏览器对当前事件的默认行为
  • stopPropagation方法阻止事件在 DOM 中继续传播,防止再触发定义在别的节点上的监听函数,但是不包括 在当前节点上其他的事件监听函数。

利用原型属性自定义内置函数#

//删除指定下标的元素
Array.prototype.removeAt = function (index) {
if (isNaN(index) || index > this.length) {
return; //index输入不合理,直接结束对象
}
this.splice(index, 1);
};
let arr= [1,2,3];
arr.removeAt(0);
console.log(arr); //[ 2, 3 ]

JSON.stringify()#

  • 简单说就是将js对象转换成json格式的字符串

闭包#

let func = function () {
let a = "hqjy";
let func1 = function () {
a += " a";
console.log(a);
};
return func1;
};
let fun2 = func();
fun2();
fun2();
  • 闭包导致 局部变量a生命周期延长
  • 输出:
  • hqjy a hqjy a a
for (var i = 0; i < 4; i++) {
setTimeout(function () {
console.log(i);
}, 0);
}
4
4
4
4
for (let i = 0; i < 4; i++) {
setTimeout(function () {
console.log(i);
}, 0);
}
0
1
2
3

构造函数#

function demo(){
this.name="feifei";
this.say = function(){
console.log("嘻嘻");
}
return this;
}
let d = new demo();
console.log(d.name);
d.say();
demo().say();

feifei 嘻嘻 嘻嘻

原型链#

实例的隐式原型属性, 永远指向缔造者的原型对象#

function Student(name, age) {
this.name = name;
this.age = age;
this.study = function() {
console.log('学习');
}
}
const stu = new Student("张三", 18);
console.log(stu);
// 显式原型属性 (原型对象)
console.log(Student.prototype);
// 隐式原型属性
console.log(stu.__proto__);
console.log(stu.__proto__ === Student.prototype); // true
const stu1 = new Student('李四', 20);
Student.prototype.say = function() {
console.log('说话');
}
stu.say();
stu1.say();
stu.__proto__.say1 = function() {
console.log('说话1');
}
// stu1也能输出say1方法, 实例的隐式原型属性和Student的显示原型对象指向 相同
stu.say1();
stu1.say1();
ES6新语法
https://blog.tiamix.cn/posts/es6新语法/
作者
Tiam
发布于
2022-12-26
许可协议
CC BY-NC-SA 4.0