下面都是开发🔥必用的语法.
let
定义变量, 区别于"var", 他所声明的变量只在"let"所在的代码块内有效, 总之一句话: "var"就不要用了, 都替换成"let".
{
let a = 10;
var b = 1;
}
a // ReferenceError: a is not defined.
b // 1
const
定义常量, 定义后的变量不可修改
const PI = 3.1415;
PI // 3.1415
PI = 3;
// TypeError: Assignment to constant variable.
数组解构赋值
let [a, b, c] = [1, 2, 3];
// 等价
let a = 1;
let b = 2;
let c = 3;
对象的解构赋值
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x // 1
y // 2
z // { a: 3, b: 4 }
函数参数的解构赋值
function add([x, y]){
return x + y;
}
add([1, 2]); // 3
function move({x, y} = { x: 0, y: 0 }) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
模板字符串
字符串中可以优雅的插入变量.
const a = '你好';
const b = `${a} Vue`;
// b == '你好vue'
函数参数默认值
function add(a,b=1){
return a+b;
}
add(3) // 4
箭头函数
function a(){
return '你好'
}
// 箭头函数
const a = ()=>{
return '你好';
}
// 还可以更简单
const a = ()=>'你好'
数组的扩展运算符
// 等价于 console.log(1,2,3);
console.log(...[1, 2, 3]);
// 合并数组
const a = [1,2,3];
const b = [...a,4,5]; // [1,2,3,4,5]
对象属性的简洁表示法
const a = 1;
const obj = {a: 1};
// 简写
const obj = {a}; // {a: 1}
对象方法的简洁表示法
const obj = {
say:function (){
return '你好!';
}
};
// 简写,可以省略":function"
const obj = {
say (){
return '你好!';
}
};
对象属性名表达式
对象的属性名可以支持变量.
const a = 'abc';
let obj = {};
obj[`${a}123`] = 1;
console.log(obj) // {abc123:1};
链判断运算符(?)
实现对"?"左边的表达式是否为null或者undefined的判断, 如果是立即停止判断, 返回undefined或null.
const firstName = (message
&& message.body
&& message.body.user
&& message.body.user.firstName);
// 简写
const fristName = message?.body?.user?.firstName;
Null判断运算符(??)
console.log(0 ?? 1); // 0
console.log(false ?? 1); // false
console.log(undefined ?? 1); // 1
console.log(null ?? 1); // 1
很显然只有"??"前面的值是null或undefined才返回"??"后面的值.
Promise
Promise 是异步编程的一种解决方案,比传统的解决方案"回调函数和事件"更合理. 在这里大概了解下即可, 主要是为了讲解后面的"async/await", 因为在开发中我们使用的第三方插件很多都是封装成Promise格式的, 初期需要自己封装的需求很少.
// 封装代码成Promise格式
const promiseA = ()=> new Promise(function(resolve, reject) {
// === 你的代码 ===
setTimeout(()=>{
if(0.5 < Math.random()){
resolve('成功');
} else {
reject('失败');
}
},200);
// === 你的代码 ===
});
// 执行
promiseA().then(value=>{
// '成功' == value
console.log(value);
}).catch(error=>{
// '失败' == error
console.log(error);
});
async/await
执行Promise函数"更优雅". 用上面封装"promiseA函数"为例:
function funA(){
promiseA().then(value=>{
console.log(value);
}).catch(error=>{
console.log(error);
});
}
// 改写, 需要用try/catch来捕获"reject"触发的异常
async function funA(){
try{
const value = await promiseA();
console.log(value);
} catch(error){
console.log(error);
}
}
更多
在这里我只是给大家讲解了几个常用的语法, 更多请参考阮一峰老师的教程
⚡ 在线视频
微信群
感谢大家的阅读, 如有疑问可以加我微信, 我拉你进入微信群(由于腾讯对微信群的200人限制, 超过200人后必须由群成员拉入)