脚本宝典收集整理的这篇文章主要介绍了ES6常用实例,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
属性名表达式
VAR obj = {
['student_' + '1_name']: 'jack',
['say' + 'hello']() { //
return 'hi';
}
};
console.LOG(obj.student_1_name);//jack
console.log(obj.sayhello());//hi
属性的简洁表示法
var b = {foo} // b = {foo:foo}
//ES6 允许在对象之中,直接写变量。这时,属性名为变量名, 属性值为变量的值
function getPoint() {
const x = 1;
const y = 10;
return {x, y};
}
getPoint();// {x:1, y:10}
解构赋值
交换变量
var x=1,y=2;
[x,y]=[y,x];
console.log(x);//2
提取JSON数据,比如从后台拿回来的返回值
var {res,code} = {res:
{
data: [1,2,4],
total: 3
},code:200};
console.log(res.total);//3
函数无序传参
function name({ x, y, z }) {
console.log(z);
}
name({ z: 6, y: 2, x: 4 });//6
函数传参可以设置默认值
function name({ x = 1, y, z }) {
console.log(x);
}
name({ z: 6, y: 2});
输入模块的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map");
import { func1 , func2 } From '../common.js'
扩展运算符
取代concat合并数组
let arr1=[1,2,3],
arr2 = [4,5],
all = [...arr1,...arr2];
console.log(all);//[1,2,3,4,5]
var First = [1, 2, 3],
second = [2],
[first, second, ...last] = [1, 2, 3, 4, 5];
console.log(last);//[3,4,5]
var arr = [...'hello'];
console.log(arr);//["h", "e", "l", "l", "o"]
字符串扩展
字符串补全长度
//补全指定位数
'1'.padStart(10,'0');//"0000000001"
数组扩展
使用 Array.from 方法,将类似数组的对象转为数组
const foo = document.querySelectorAll('div');
const nodes = Array.from(foo);
async函数
函数前面的async关键字,表明该函数内部有异步操作。
async function getStockPRiceByName(name) {
const symbol = await getStockSymbol(name);
const stockPrice = awaIT getStockPrice(symbol);
return stockPrice;
}
getStockPriceByName('goog').then(function (result) {
console.log(result);
});
async函数返回一个 Promise 对象。
//另一个栗子:
function timeout(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function asyncPrint(value, ms) {
await timeout(ms);
console.log(value);
}
asyncPrint('hello world', 50);
async函数内部return语句返回的值,会成为then方法回调函数的参数。
//栗子
async function f() {
return 'hello world';
}
f().then(v => console.log(v))
// "hello world"
多个await命令后面的异步操作
let [foo, bar] = await Promise.all([getFoo(), getBar()]);
class的继承
class point {
constructor(x,y) {
this.x = x;
this.y = y;
}
toString() {
return '('+ this.x + ',' + this.y + ')';
}
}
class circlePoint extends point {
constructor(x,y,color) {
suPEr(x, y);
this.color = color;
}
toString() {
return this.color + '' + super.toString();
}
}
console.log(new circlePoint(1,2,'red').toString()); //red(1,2)
Module 的语法
export与export default的区别
1、在一个文件或模块中,export、import可以有多个,export default仅有一个
2、通过export方式导出,在导入时要加{ },export default则不需要
以上是脚本宝典为你收集整理的ES6常用实例全部内容,希望文章能够帮你解决ES6常用实例所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。