解构赋值
// 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;
}