ES6 奇技淫巧 总结

解构赋值

// a与b的值互换
[a, b] = [b, a];

let list = [1, 2, 3, 4]
let [first, ...rest] = list;
等价于
let rest = list.slice(1); // [2, 3, 4];
let first = list[0]; // 1

[foo, bar] = [100, 'hello world!'];
等价于
let foo = 100;
let bar = 'hello world!';

链判断运算符

const firstName = message 
                    && message.body 
                    && message.body.user
                    && message.body.user.firstName || 'default';
const firstName = message?.body?.user?.firstName || 'default';

逻辑赋值运算符 

// 或赋值运算符
x ||= y
// 等同于
x || (x = y)

chartType.type ||= 'min';
等同于
chartType.type || chartType.type='min';

------------------------------ 为变量或属性设置默认值---------------------------

// Null 赋值运算符
x ??= y
// 等同于
x ?? (x = y)

chartType.type ??= 'min';
等价于
chartType.type ?? (chartType.type='min');

函数的参数默认值

利用参数默认值,可以指定某一个参数不得省略,如果省略就抛出一个错误

function throwIfMissing() {
    throw new Error('Missing parameter');
}

function foo(mustBeProvided = throwIfMissing()) {
    return mustBeProvided;
}

foo()
// Error: Missing parameter

 大整数(BigInt)

计算时结果取整

9n / 5n = 1n

 Set 数据结构

利用 Set 数据结构进行数组去重

let arr = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5];
let newArr = [...new Set(arr)]; // [1, 2, 3, 4, 5]

 Promise 相关

function fetch(method, url, data){
    return new Promise((resolve, reject) => {
        var xhr = new XMLHttpRequest();
        var method = method || "GET";
        var data = data || null;
        xhr.open(method, url, true);
        xhr.onreadystatechange = function() {
            if(xhr.status === 200 && xhr.readyState === 4){
                resolve(xhr.responseText);
            } else {
                reject(xhr.responseText);
            }
        }
        xhr.send(data);
    })
}
两列布局:双飞燕布局,左侧固定200px;右侧自适应
// html
<div class='wrap'>
	<div class="left"></div>
	<div class="right">555555555</div>
</div>

// css
.wrap{
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: flex-start;
}
.left{
	background: red;			
	flex: 0 0 200px;
}
.right{
	background: blue;
	flex: 1;
}

同理,上下布局,上面高度200px,下面高度自适应:
// html
<div class='wrap'>
	<div class="top"></div>
	<div class="bottom">555555555</div>
</div>

// css
.wrap{
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: flex-start;
}
.top{
	background: red;			
	flex: 0 0 200px;
}
.bottom{
	background: blue;
	flex: 1;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值