关于javascript:结构赋值

7次阅读

共计 1129 个字符,预计需要花费 3 分钟才能阅读完成。

// 1. 替换变量的值

let x =1;
let y = 2;
[x,y] = [y,x] // 2. 从函数返回多个值
// 函数只能返回一个值 若要返回多个 
// 能够放在数组或对象里返回 还能够利用解构赋值
function example(){ return [1,2,3];
}
let [a,b,c] = example();
example() // 返回一个数组

function example(){ return{
        foo:1,
        bar:2 };
}
let {foo,bar} = example(); // 返回一个对象

// 3. 函数参数的定义
// 参数是一组有序的值
function f([x,y,z]){...}
f([1,2,3]); // 参数是一组无序的值
function f({x,y,z}){...}
f({z:3,y:2,x:1}) // 4. 提取 json 数据
let jsonData = {
    id:42,
    status:'ok',
    data:[867,5309]

};
let {id,status,data:number} = jsonData;
console.log(id,status,number) // 5. 函数参数的默认值
jQuery.ajax = function (url,{
    async = true,
    beforeSend = function(){},
    cache = true,
    complete = function(){},
    crossDomain = false,
    global = true,
} = {}){

} // 6. 遍历 Map 解构
const map = new Map();
map.set('first','hello')
map.set('last','world') for(let [Key,value] of map){console.log(key + 'is' + value);
    
}

; “ 复制代码 ”)

函数参数的解构赋值

; “ 复制代码 ”)

function add([x,y]){return x + y;

}
add([1,2]) // add 的参数外表是数组 但在传参时 数组参数被解构为 x 和 y 

[[1,2],[3,4]].map(([a,b]) => a +b) //[3,7]

; “ 复制代码 ”)

数值和布尔值的解构赋值

; “ 复制代码 ”)

// 解构赋值时 等号左边是数值或布尔值时 则会先转为对象

let {toStrig:s} = 123;
s === Number.prototype.toString//true
let {toString:s} = true;
s === Boolean.prototype.toStrig;//true
// 数值和布尔值的包装对象都有 toString 属性 因而变量 s 都能取到值



// 解构赋值准则 只有等号左边的值不是对象或数组 
// 就先将其转换为对象 因为 null 和 undefined 无奈转换为对象 所以解构赋值会报错 
正文完
 0