函数默认值

面试中可能会问到下面问题

function say(a = 1) {
  console.log(a);
}
say(null);
say(undefined);
say();
say(0);
console.log(say.length); // say.length表示函数形参个数

关于答案,我先卖个关子,相信你看了下面的解析就会被安排的明明白白。

基本用法

  • 1个参数有默认值
// ES6代码
function say(a = 1) {
  console.log(a);
}

// 转为ES5代码
function say() {
  var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
  console.log(a);
} 

看到这里,上面的问题你应该就彻底明白啦。。。你可以很自信的在控制台里面验证一下你的答案啦。但是,别着急,接着往下看👇,你会收获更多。

  • 多个参数第一个有默认值
// ES6代码
function say(a = 1, b, c) {
  console.log(a);
  console.log(b);
  console.log(c);
}

// 转为ES5代码
function say() {
  var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
  var b = arguments.length > 1 ? arguments[1] : undefined;
  var c = arguments.length > 2 ? arguments[2] : undefined;
  console.log(a);
  console.log(b);
  console.log(c);
}

哈哈,是不是跟自己想的不太一样呢?

  • 多个参数第一个无默认值
// ES6代码
function say(a, b = 1, c) {
  console.log(a);
  console.log(b);
  console.log(c);
}

// 转为ES5代码
function say(a) {
  var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  var c = arguments.length > 2 ? arguments[2] : undefined;
  console.log(a);
  console.log(b);
  console.log(c);
}

还有这样子

// ES6代码
function say(a, b, c = 1) {
  console.log(a);
  console.log(b);
  console.log(c);
}

// 转为ES5代码
function say(a, b) {
  var c = arguments.length > 2 && arguments[1] !== undefined ? arguments[1] : 1;
  console.log(a);
  console.log(b);
  console.log(c);
}

这样子。。。

// ES6代码
function say(a = 1, b, c = 1) {
  console.log(a);
  console.log(b);
  console.log(c);
}

// 转为ES5代码
function say() {
  var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
  var b = arguments.length > 1 ? arguments[1] : undefined;
  var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  console.log(a);
  console.log(b);
  console.log(c);
}

还有其他情况就不一一列举啦。

未完待续。。。

其他高级点的用法会在后续补充哦。

写文不易,喜欢的朋友可以点个关注留个赞。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章