七、函数参数默认值

郁子小于 1 分钟约 170 字笔记ECMAScript尚硅谷李强

  • ES6 允许给函数参数赋初始值

(一)形参的初始值

  • 具有默认值的参数,一般位置要靠后(潜规则)
function add(a, b, c) {
  return a + b + c;
}
console.log(add(1, 2, 3));
// 6
console.log(add(1, 2));
// NaN【c = undefined】

function add2(a, b, c = 10) {
  return a + b + c;
}
console.log(add2(1, 2));
// 13

(二)可以与解构赋值结合

// function connect(options) {
//   let host = options.host;
//   let username = options.username;
//   let password = options.password;
//   let port = options.port;
// }

function connect({ host = "127.0.0.1", username, password, port }) {
  console.log(host);
  console.log(username);
  console.log(password);
  console.log(port);
}
// localhost // 127.0.0.1
// root
// root
// 3306

connect({
  // host: 'localhost',
  username: "root",
  password: "root",
  port: 3306,
});
上次编辑于: