默认值设置
默认参数的基本用法
ES6允许在函数定义时为参数设置默认值。当调用函数时没有提供相应参数或参数值为undefined
时,就会使用默认值。这种语法比ES5中通过逻辑或操作符设置默认值的方式更加直观和可靠。
// ES5方式
function multiply(a, b) {
b = b || 1;
return a * b;
}
// ES6方式
function multiply(a, b = 1) {
return a * b;
}
console.log(multiply(5)); // 5
console.log(multiply(5, 2)); // 10
默认参数与解构赋值结合
默认参数可以与解构赋值结合使用,为解构后的变量提供默认值。这种方式在处理复杂对象参数时特别有用。
// 对象解构与默认值
function drawChart({size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}) {
console.log(size, coords, radius);
}
drawChart({
coords: {x: 18, y: 30},
radius: 30
});
// 输出: big {x: 18, y: 30} 30
// 数组解构与默认值
function createMenu([starter = 'salad', main = 'pasta', dessert = 'cake'] = []) {
return {starter, main, dessert};
}
console.log(createMenu(['soup']));
// 输出: {starter: "soup", main: "pasta", dessert: "cake"}
默认参数的求值时机
默认参数不是在函数定义时求值,而是在函数调用时求值。这意味着每次调用函数时,如果参数未提供,都会重新计算默认值。
let count = 0;
function getValue() {
return count++;
}
function add(a, b = getValue()) {
return a + b;
}
console.log(add(1)); // 1 (count=0)
console.log(add(1)); // 2 (count=1)
console.log(add(1, 1)); // 2 (count=1)
默认参数的作用域
默认参数会形成一个单独的作用域,这个作用域在函数体作用域之前创建。这意味着默认参数中定义的变量不能在函数体内部访问。
function outer(x = 1) {
function inner(y = 2) {
console.log(x + y); // 可以访问x
}
inner();
}
outer(); // 3
function example(a = b, b = 2) {
console.log(a, b);
}
example(); // 报错,b未定义
默认参数与arguments对象
当使用默认参数时,arguments对象的行为与不使用默认参数时不同。在严格模式下,arguments对象不会反映参数的更改。
function foo(a, b = 2) {
console.log(arguments.length);
console.log(a === arguments[0]);
console.log(b === arguments[1]);
a = 10;
b = 20;
console.log(a === arguments[0]);
console.log(b === arguments[1]);
}
foo(1);
// 输出:
// 1
// true
// false
// false
// false
默认参数的实际应用
默认参数在实际开发中有多种应用场景,下面是一些常见用例:
- 配置对象处理:
function createElement(tag, {className = '', id = '', textContent = ''} = {}) {
const el = document.createElement(tag);
el.className = className;
el.id = id;
el.textContent = textContent;
return el;
}
const div = createElement('div', {className: 'box', id: 'main'});
- API请求默认值:
async function fetchData(url, {method = 'GET', headers = {}, body = null} = {}) {
const response = await fetch(url, {
method,
headers: new Headers(headers),
body: body ? JSON.stringify(body) : null
});
return response.json();
}
fetchData('/api/users', {method: 'POST', body: {name: 'John'}});
- 数学计算函数:
function calculateTotal(price, taxRate = 0.1, discount = 0) {
return price * (1 + taxRate) * (1 - discount);
}
console.log(calculateTotal(100)); // 110
console.log(calculateTotal(100, 0.2)); // 120
console.log(calculateTotal(100, 0.2, 0.1)); // 108
默认参数的注意事项
使用默认参数时需要注意以下几点:
- 默认参数不会跳过参数位置:
function f(a = 1, b = 2, c = 3) {
console.log(a, b, c);
}
f(undefined, null, 4); // 1 null 4
- 默认参数可以是函数调用:
function getDefaultValue() {
return 42;
}
function fn(value = getDefaultValue()) {
console.log(value);
}
fn(); // 42
- 默认参数可以是前面的参数:
function createUser(name, nickname = name) {
return {name, nickname};
}
console.log(createUser('Alice')); // {name: "Alice", nickname: "Alice"}
- 默认参数不能访问函数体内声明的变量:
function example(a = b) {
let b = 2;
console.log(a);
}
example(); // 报错,b未定义
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn