让学习“上瘾”,成为更好的自己!!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>函数参数的解构赋值</title>
</head>
<body>
<script>
// (1) 函数的参数也可以使用解构赋值
function add([x, y]){
return x + y;
}
// console.log(add([12, 3]));
var nums = [[1, 2], [3, 4]];
var result = nums.map(([a, b]) => a + b);
// console.log(result); // [3, 7]
// (2) 函数参数的解构也可以使用默认值
function move({x = 0, y = 0} = {}){ // 写法一
// 函数move的参数是一个对象,对这个对象进行解构,得到变量x和y的值,且为x and y指定了默认值
console.log([x, y]);
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]
// 当默认值生效时,x and y 等于默认值
// 【写法不同,结果不同】
// function move({x, y} = {x: 0, y: 0}){ // 写法二
// // 为函数move的参数(一个对象)指定默认值,而不是为变量x and y指定默认值,因此结果不一样
// console.log([x, y]);
// }
// move({x: 3, y: 8}); // [3, 8]
// move({x: 3}); // [3, undefined]
// move({}); // [undefined, undefined]
// move(); // [0, 0]
// function move(x = 0, y = 0){ // 写法三
// console.log([x, y]);
// }
// move({x: 3, y: 8}); // [{x: 3, y: 8}, 0]
// move({x: 3}); // [{x:3}, 0]
// move({}); // [{}, 0]
// move(); // [0, 0]
// undefined会触发函数参数的默认值
var nums2 = [1, undefined, 3];
var result2 = nums2.map((x = 'yes') => x);
// console.log(result2); // [1, "yes", 3]
</script>
</body>
</html>