es6基础
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了es6基础,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含13297字,纯文字阅读大概需要19分钟。
内容图文
分模块引入,回调地狱,this 指向不明 es6优势
Promise
是异步编程的一种解决方案
容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果。从语法上说,Promise是一个对象,从它可以获取异步操作的消息
(1)对象的状态不受外界影响
(2)一旦状态改变,就不会再变,任何时候都可以得到这个结果(此有点即缺点,无法中途取消)
var promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 异步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
异步加载 图片 eg:
function LoadImageAsync(url){
var promise = new Promise(function(resolve,reject){
var image = new Image();
image.onload = function(){
resolve();
};
image.onerror = function(){
reject(new Error(‘Could not load image ‘));
};
image.url = url;
});
}
LoadImageAsync("image/touxiang.jpg");
ajax
getJSON("/post/1.json").then(
post => getJSON(post.commentURL)
).then(//请求之后指定函数(Resolved or Rejected)
comments => console.log("Resolved: ", comments),
err => console.log("Rejected: ", err)
).catch(function(error) {
// 处理 getJSON 和 前一个回调函数运行时发生的错误
console.log(‘ 发生错误! ‘, error);
});
let o = new Promise(function (resolve,reject){ consle.log(‘1‘);
resolve(‘2‘);
})
o.then(
function(val)(
console.log(val)
))
console.log(‘3‘);
对象扩展
Object.assign() (undefined和null 无法转成对象,所以如果它们作为参数,就会报错)
对象的合并,将源对象(source)的所有可枚举属性,复制到目标对象(target)
var target = { a: 1 };
var source1 = { b: 2 };
var source2 = { c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
第一个参数是目标对象,后面的参数都是源对象
目标对象与源对象有同名属性,或多个源对象有同名属性,则后面的属性会覆盖前面的属性
var target = { a: 1, b: 1 };
var source1 = { b: 2, c: 2 };
var source2 = { c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
Symbol
ES6 引入了一种新的原始数据类型 Symbol ,表示独一无二的值。它是 JavaScript 语言的第七种数据类型,前六种是: Undefined 、 Null 、布尔值( Boolean )、字符串( String )、数值( Number )、对象( Object )。
// 有无参数 都不全等
var s1 = Symbol("foo");
var s2 = Symbol("foo");
s1 === s2 // false
Symbol 值不能与其他类型的值进行运算,会报错。但可以显式转换为字符串
...待续
Proxy 用于修改某些操作的默认行为(代理)
new Proxy()表示生成一个 Proxy 实例
target 参数表示所要拦截的目标对象
handler参数也是一个对象,用来定制拦截行为
var proxy = new Proxy(target, handler);
... //未完
函数扩展
ES6 函数参数默认值
function log(x, y = ‘World‘) {//直接在参数定义的后边
console.log(x, y);
}
log(‘Hello‘) // Hello World
log(‘Hello‘, ‘China‘) // Hello China
log(‘Hello‘, ‘‘) // Hello
参数变量是默认声明的,所以不能用 let 或 const 再次声明!!
function foo({x, y = 5}) {
console.log(x, y);
}
foo({}) // undefined, 5 //参数格式匹配
foo() // TypeError: Cannot read property ‘x‘ of undefined//参数格式不匹配
foo({x: 1}) // 1, 5
foo({x: 1, y: 2}) // 1, 2
非尾部的参数设置默认值,实际上这个参数是没法省略的
function f(x = 1, y) {
return [x, y];
}
f() // [1, undefined]
f(2) // [2, undefined])
f(, 1) // 报错
length 属性,返回没有默认值的参数个数。(默认值不计算在内)
(fun(a){}).length//1
作用域
function f(y = x) {
let x = 2;
console.log(y);
}
f() // ReferenceError: x is not defined
rest 参数 只能放在最后 (...values)
fun(a,b,...c){}
<br>
var arr1 = [‘a‘, ‘b‘];
var arr2 = [‘c‘];
var arr3 = [‘d‘, ‘e‘];
// ES5 的合并数组
arr1.concat(arr2, arr3);
// [ ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘ ]
// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘ ]
函数名查询,匿名函数时ES5为"",ES6为声明的名字。
const bar = function baz() {};
// ES5
bar.name // "baz"
// ES6
bar.name // "baz"
=>
var f = v => v;
等同于
var f = function(v){
return v;
}
eg:只有一个 this ,就是函数 foo 的 this
function foo() {
return () => {
return () => {
return () => {
console.log(‘id:‘, this.id);
};
};
};
}
var f = foo.call({id: 1});
var t1 = f.call({id: 2})()(); // id: 1
var t2 = f().call({id: 3})(); // id: 1
var t3 = f()().call({id: 4}); // id: 1
arr.splice(index,howmany,element)
1、index---------从该下标开始删除
2、howmany----删除指定数量的元素
3、elements-----插入的元素
函数绑定
双冒号左边是一个对象,右边是一个函数。该运算符会自动将左边的对象,作为上下文环境(即 this 对象),绑定到右边的函数上面
foo::bar;
等同于
bar.bind(foo);
foo::bar(...arguments);
// 等同于
bar.apply(foo, arguments);
双冒号左边为空,右边是一个对象的方法,则等于将该方法绑定在该对象上面
var method = obj::obj.foo;
// 等同于
var method = ::obj.foo;
let log = ::console.log;
// 等同于
var log = console.log.bind(console);
尾调用优化
某个函数的最后一步是调用另一个函数(并非是放在函数最后,是最后一步操作)
eg://尾调用
function f(x){
return g(x);
}
//非尾调用
function f(x){
g(x);
} 等同于
function f(x){
g(x);
return undefined;
}
数组扩展
Array.from()
Array.from 方法用于将两类对象转为真正的数组
let arrayLike = {
‘0‘: ‘a‘,
‘1‘: ‘b‘,
‘2‘: ‘c‘,
length: 3
};
// ES6 的写法
let arr2 = Array.from(arrayLike); // [‘a‘, ‘b‘, ‘c‘]
// NodeList 对象
let ps = document.querySelectorAll(‘p‘);
Array.from(ps).forEach(function (p) {
console.log(p);
});
Array.of 方法用于将一组值,转换为数组
Array.of(3, 11, 8) // [3,11,8]
Array.of(3, 11, 8).length // 3
copyWithin()
指定位置的成员复制到其他位置,会覆盖原有成员
Array.prototype.copyWithin(target, start = 0, end = this.length)
target (必需):从该位置开始替换数据。
start(可选):从该位置开始读取数据,默认为0。如果为负值,表示倒数。
end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。
// 将 3 号位复制到 0 号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]
find() 和 findIndex()
[1, 4, -5, 10].find((n) => n < 0)
// -5
fill 方法使用给定值,填充一个数组
[‘a‘, ‘b‘, ‘c‘].fill(7)
// [7, 7, 7]
new Array(3).fill(7)
// [7, 7, 7]
[‘a‘, ‘b‘, ‘c‘].fill(7, 1, 2)//(填充元素,起始位,结束位)
// [‘a‘, 7, ‘c‘]
ES6 提供三个新的方法,arr.entries(),arr.keys()和arr.values()用于遍历数组
for(let index of [‘a‘,‘b‘].keys()){
console.log(index);
}
// 0
// 1
for (let elem of [‘a‘, ‘b‘].values()) {
console.log(elem);
}
// ‘a‘
// ‘b‘
for (let [index, elem] of [‘a‘, ‘b‘].entries()) {
console.log(index, elem);
}
// 0 "a"
// 1 "b"
includes()
[1, 2, 3].includes(2); // true//两个参数时(包含的元素,元素的位置{可为负})
indexOf() 方法有两个缺点
一是不够语义化,不等于 -1 时存在
二是内部使用严格相当运算符( === )进行判断,对NaN的误判
[NaN].indexOf(NaN)
// -1
[NaN].includes(NaN)
// true
Map 结构的 has 方法,是用来查找键名的
Map.prototype.has(key)、WeakMap.prototype.has(key)、Reflect.has(target,propertyKey)。
Set 结构的 has 方法,是用来查找值的
Set.prototype.has(value) 、 WeakSet.prototype.has(value)
空位
Array(3) // [, , ,]// 无值
0 in [undefined, undefined, undefined] // true//有值
0 in [, , ,] // false // 无值
ES6 则是明确将空位转为 undefined (ES5 不是)
Array.from([‘a‘,,‘b‘])
// [ "a", undefined, "b" ]
entries()、keys()、values()、find() 和findIndex()会将空位处理成 undefined
// entries()
[...[,‘a‘].entries()] // [[0,undefined], [1,"a"]]
// keys()
[...[,‘a‘].keys()] // [0,1]
// values()
[...[,‘a‘].values()] // [undefined,"a"]
// find()
[,‘a‘].find(x => true) // undefined
// findIndex()
[,‘a‘].findIndex(x => true) // 0
map 方法遍历,空位是会跳过 !!!
空位的处理不统一,避免出现空位
RegExp 构造函数
字符串对象共有 4 个方法,可以使用正则表达式: match() 、 replace() 、 search() 和 split()
String.prototype.match 调用 RegExp.prototype[Symbol.match]
String.prototype.replace 调用 RegExp.prototype[Symbol.replace]
String.prototype.search 调用 RegExp.prototype[Symbol.search]
String.prototype.split 调用 RegExp.prototype[Symbol.split]
u 修饰符
含义为 “Unicode 模式 ” ,正确处理四个字节的 UTF-16 编码
点( . )字符在正则表达式中,含义是除了换行符以外的任意单个字符码点大于 0xFFFF 的Unicode 字符不能识别,必须加上 u 修饰符
RegExp.escape()
字符串必须转义,才能作为正则模式
ES6 标签模板
$("#result").append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`);
模板表达式计算
var x = 1;
var y = 2;
`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"
模板字符串之中调用函数
function fun() {
return "nihao sx";
}
`foo ${fun()} bar`
// foo Hello World bar //vue 中调用`foo ${this.fun()} bar`
String.raw()
用来充当模板字符串的处理函数,返回一个斜杠都被转义
函数运用,正常函数...
ES7 补全 padStart() , padEnd()
‘x‘.padStart(5, ‘ab‘) // ‘ababx‘ //(位数,‘填补内容’)
等于或大于指定的最小长度,则返回原字符串
repeat()
‘x‘.repeat(3) // "xxx"
es6 for...of 循环会正确识别出这一个字符
字符串扩展 4 个字节储存的字符
var s = "吉";
s.length // 2
s.charAt(0) // ‘‘
s.charAt(1) // ‘‘
s.charCodeAt(0) // 55362
s.charCodeAt(1) // 57271
es6 codePointAt()
var s = ‘吉a‘;
s.codePointAt(0) // 134071
s.codePointAt(1) // 57271
s.charCodeAt(2) // 97
//转16进制
s.codePointAt(0).toString(16) // "20bb7"
s.charCodeAt(2).toString(16) // "61"
fromCodePoint()//转回汉字
String.fromCodePoint(0x20BB7)
// "吉"
结构赋值用途
( 1 )交换变量的值
[x, y] = [y, x];
( 2 )从函数返回多个值
function a(){
return [1,2,4];
}
var [a,b,c] = a();
( 3 )函数参数的定义
// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
( 4 )提取 JSON 数据
var jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]
( 5 )函数参数的默认值
( 6 )遍历 Map 结构
var map = new Map();
map.set(‘first‘, ‘hello‘);
map.set(‘second‘, ‘world‘);
for (let [key, value] of map) {
console.log(key + " is " + value);
}
// first is hello
// second is world
只想获取键名
// 获取键名
for (let [key] of map) {
// ...
}
// 获取键值
for (let [,value] of map) {
// ...
}
ES6 的规则是,只要有可能导致解构的歧义,就不得
使用圆括号
(1)变量声明语句中,不能带有圆括号
(2)函数参数中,模式不能带有圆括号
函数参数也属于变量声明,因此不能带有圆括号
(3)赋值语句中,不能将整个模式,或嵌套模式中的一层,放在圆括号之中
// 全部报错
var [(a)] = [1];
var {x: (c)} = {};
var ({x: c}) = {};
var {(x: c)} = {};
var {(x): c} = {};}
var { o: ({ p: p }) } = { o: { p: 2 } };
function f([(z)]) { return z; }
({ p: a }) = { p: 42 };
([a]) = [5];
[({ p: a }), { x: c }] = [{}, {}];
可以使用圆括号的情况只有一种:赋值语句的非模式部分,可以使用圆括号
模式是取数组的一个成员,跟圆括号无关
[(b)] = [3]; // 正确 赋值语句,而不是声明语句
[(parseInt.prop)] = [3]; // 正确 赋值语句,而不是声明语句
({ p: (d) } = {}); // 正确 //模式是 p ,而不是 d
函数参数结构
move 的参数是一个对象,通过对这个对象进行解构,得到变量 x 和 y 的值。如果解构失败, x 和 y 等于默认值
eg1:
function move({x = 0, y = 0} = {}) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]
eg2:
function move({x, y} = { x: 0, y: 0 }) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]
数值和布尔值的解构赋值
解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
字符串解构赋值
const [a, b, c, d, e] = ‘hello‘;
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
对象的解构赋值
数组的元素是按次序排列的
而对象的属性没有次序,变量必须与属性同名
var { bar, foo } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
//真正被赋值的是后者,而不是前者
var { foo: baz } = { foo: "aaa", bar: "bbb" };
baz // "aaa"
foo // error: foo is not defined
const 声明一个只读常量。 声明赋值 之后不可改变。
ES6 允许块级作用域的任意嵌套。
内层作用域可以定义外层作用域的同名变量。
外层作用域无法读取内层作用域的变量。
{{
let insane = ‘Hello World‘;
{ let insane = ‘Hello World‘ }
}};
{
let a = ‘secret‘;
function f() {
return sx;
}
}
f(); // 报错
模块封装
import { identifier1, identifier2 } from "./example.js";
一是需要导入的标识符,二是需导入的标识符的来源模块
//多个导入
import { sum, multiply, magicNumber } from "./example.js";
console.log(sum(1, magicNumber)); // 8
console.log(multiply(1, 2)); // 2
从 example 模块导入了三个绑定: sum 、 multiply 与 magicNumber ,之后便可以使
用它们,仿佛它们是在当前模块中被定义的
// 完全导入
import * as example from "./example.js";
//更名
import { add as sum } from "./example.js";
console.log(typeof add); // "undefined"
console.log(sum(1, 2)); // 3
导入了 add() 函数,并使用了导入名称( import name )将其重命名为 sum()(本地名称),此模块已不存在add()
ES6
尾调用 某函数最后一步调用另一个函数,
function f(x){
return g(x);
}
一般递归
function factorial(n) {
if (n === 1) return 1;
return n * factorial(n - 1);
}
factorial(5) // 120 //n个帧,会栈溢出(stack overflow)
尾递归
function factorial(n, total) {
if (n === 1) return total;
return factorial(n - 1, n * total);
}
factorial(5, 1) // 120 //只有一个帧,不会栈溢出
ES5,ES6 不同
function f() { console.log(‘I am outside!‘); }
(function () {
function f() { console.log(‘I am inside!‘); }
if (false) {
}
f();
}());
ES6的运行结果,得到“I am outside!”
解构赋值
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
var { foo: baz } = { foo: "aaa", bar: "bbb" };
baz // "aaa"
foo // error: foo is not defined
上面代码中,真正被赋值的是变量baz,而不是模式foo
var jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]
上面代码可以快速提取 JSON 数据的值
(1)变量声明语句中,不能带有圆括号
// 全部报错
var [(a)] = [1];
var {x: (c)} = {};
var ({x: c}) = {};
var {(x: c)} = {};
var {(x): c} = {};}
var { o: ({ p: p }) } = { o: { p: 2 } };
(2)函数参数中,模式不能带有圆括号
函数参数也属于变量声明,因此不能带有圆括号。
// 报错
function f([(z)]) { return z; }
(3)赋值语句中,不能将整个模式,或嵌套模式中的一层,放在圆括号之中。
//报错
({ p: a }) = { p: 42 };
([a]) = [5];
上面代码将整个模式放在模式之中,导致报错。
// 报错
[({ p: a }), { x: c }] = [{}, {}];
上面代码将嵌套模式的一层,放在圆括号之中,导致报错
可以使用圆括号的情况只有一种:赋值语句的非模式部分,可以使用圆括号。
[(b)] = [3]; // 正确
({ p: (d) } = {}); // 正确
[(parseInt.prop)] = [3]; // 正确
for...of 循环遍历
var map = new Map();
map.set(‘first‘, ‘hello‘);
map.set(‘second‘, ‘world‘);
for (let [key, value] of map) {
console.log(key + " is " + value);
}
var o = {p: "nihao"};
map.set(o, "content")
map.get(o) // "content"
map.has(o) // true
map.delete(o) // true
map.has(o) // false
// first is hello
// second is world
// 获取键名
for (let [key] of map) {
// ...
// 获取键值
for (let [,value] of map) {
// ...
}
// 字符串的遍历 let xx of xxx
for (let codePoint of ‘foo‘) {
console.log(codePoint)
}
// "f"
// "o"
// "o"
ECMAScript引用类型
var oNumberObject = new Number(68);
alert(oNumberObject.toFixed(2)); //输出 "68.00"
var oNumberObject = new Number(68);
alert(oNumberObject.toExponential(1)); //输出 "6.8e+1" 表示 6.8x101
localeCompare()
var oStringObject = new String("yellow");
alert(oStringObject.localeCompare("brick")); //输出 "1" // Y 在B 后,输出1
alert(oStringObject.localeCompare("yellow")); //输出 "0"
slice() 和 substring()
var oStringObject = new String("hello world");
alert(oStringObject.slice("3")); //输出 "lo world"
alert(oStringObject.substring("3")); //输出 "lo world"
alert(oStringObject.slice("3", "7")); //输出 "lo w"
alert(oStringObject.substring("3", "7")); //输出 "lo w"
alert(oStringObject.slice("-3")); //输出 "rld"
alert(oStringObject.substring("-3")); //输出 "hello world"
alert(oStringObject.slice("3, -4")); //输出 "lo w"
alert(oStringObject.substring("3, -4")); //输出 "hel"
instanceof 运算符与 typeof 运算符相似,用于识别正在处理的对象的类型。与 typeof 方法不同的是,instanceof 方法要求开发者明确地确认对象为某特定类型
var oStringObject = new String("hello world");
alert(oStringObject instanceof String); //输出 "true"
var oStringObject = new String("hello world");
alert(oStringObject.charAt(1)); //输出 "e"
alert(oStringObject.charCodeAt(1)); //输出 "101" // e 的代码
原文:https://www.cnblogs.com/sx00/p/10913823.html
内容总结
以上是互联网集市为您收集整理的es6基础全部内容,希望文章能够帮你解决es6基础所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。