数值和布尔值的解构赋值
解构赋值的规则:
- 只要等于号右边的值不是对象,则优先将其转为对象
let {toString: s} = 123;
s === Number.proptotype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
函数参数的解构赋值
function add([x,y]){
retrun x + y;
}
add([1,2]) // 3
函数add的参数实际上不是一个数组,而是通过解构得到的变量x和y。
函数参数的解构依旧可以使用默认值
function move({x = 0, y = 0} = {}){
retrun [x,y]
}
move({x: 3,y: 8}); // [3,8];
move({x: 3}) // [3,0]
move({}) // [0,0]
move() // [0,0]
函数move的参数是一个对象,通过对这个对象进行解构,得到变量x和y的值。如果解构失败,则返回默认值。
下面的写法,会存在一些问题
function move({x,y} = {x: 0,y: 0}){
return [x,y];
}
move({x: 3,y: 8}); // [3,8];
move({x: 3}) // [3,undefined]
move({}) // [undefined,undefined]
move() // [0,0]
如果已经存在赋值,则会获取获取undefind
解构赋值的用途
变换变量的值
[x,y]=[y,x]
从函数中返回多个值
// 返回一个数组
function f(){
return [1,2,3];
}
var [a,b,c] = f();
// 返回一个对象
function f1(){
ruturn {
foo: 1,
bar: 2
}
}
var {foo, bar} = f1();
函数参数的定义
function f([x,y,z]){...}
f({1,2,3})
function f([x,y,z]){...}
f({x:1,z:3,y:2})
提取JSON数据
var jsonData= {
id: 42,
status: 'ok',
}
let {id,status: isok} = jsonData;
consoloe.log(id, isok); // 42 "OK"
函数参数的默认值
$.ajax=function (url,(
async = true,
beforeSend = function(){},
cache = true,
complete = function(){},
crossDomain = false,
global = true,
)){
// TODO
}
遍历Map解构
var map = new Map() ;
map.set('first', 'hello');
map.set('sec', 'world');
for(let [key, value] of map){
// 从循环的数值中依次赋值key和value
console.log(key + "is" + value)
// first is hello
// sec is world
}
输入模块的制定方法
const { SourceMapConsumer, SourceNode} = require("source-map")
圆括号的问题
- 变量声明语句中,模式中不能有圆括号
var [(a)]=[1];
var [x: {c}]={};
- 函数参数中,模式不能带有圆括号
function f([(z)]) = { return z; }
- 不能讲整个模式或嵌套模式中的一层放在圆括号中
({p: a})={p: 42}
([a]) = [5]
何正确的使用圆括号
- 赋值语句的非模式部分可以使用圆括号
[(b)] = [3];
({p: (d)} = {})