Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

变量&解构赋值 #48

Open
adodo0829 opened this issue May 3, 2020 · 0 comments
Open

变量&解构赋值 #48

adodo0829 opened this issue May 3, 2020 · 0 comments

Comments

@adodo0829
Copy link
Owner

1.变量声明

let,const用于声明变量,用来替代老语法的var关键字,与var不同的是,let/const会创建一个块级作用域{}

  • 注意事项
var在全局代码中执行, window 下
const和let只能在代码块中执行, script词法作用域下

const声明常量后必须立马赋值
let声明变量后可立马赋值或使用时赋值

不允许重复声明
未定义就使用会报错:const和let不存在变量提升
暂时性死区: 在代码块内使用const和let声明变量之前,该变量都不可用
  • 变量声明方式
var、const、let、function、class、import

2.解构赋值

// 字符串
const [a, b, c, d, e] = "hello"
// 数值, 先转包装对象; v -> f()
const { valueOf: v } = 123 
// 布尔, 先转包装对象
const { valueOf: v } = false 
// 对象
const { x, y } = { x: 1, y: 2 }
const { x, y = 2 } = { x: 1 } // y 为默认值
const { x, y: z } = { x: 1, y: 2 } // z 为改名变量
// 数组
const [x, y] = [1, 2]
const [x, y = 2] = [1] // 默认 y
// 函数参数
function fn([x = 0, y = 1] = []) {
  console.log(x, y)
} // 数组参数

function fn({ x = 0, y = 1 } = {}) {
  console.log(x, y)
} // 对象参数
  • 应用场景
交换变量值: [x, y] = [y, x]
返回函数多个值: const [x, y, z] = fn()
定义函数参数: fn([1, 2])
提取JSON数据: const { name, version } = packageJson
定义函数参数默认值: function fn({ x = 1, y = 2 } = {}) {}
遍历Map结构: for (let [k, v] of Map) {}
输入模块指定属性和方法: const { readFile, writeFile } = require("fs")
  • 注意事项
匹配模式: 只要等号两边的模式相同,左边的变量就会被赋予对应的值
解构赋值规则: 只要等号右边的值不是对象或数组,就先将其转为对象
解构默认值生效条件: 属性值严格等于undefined
解构遵循匹配模式
解构不成功时变量的值等于undefined
undefined和null无法转为对象,因此无法进行解构
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant