将特定的预定义参数传递给函数

时间:2016-12-24 17:18:02

标签: javascript function

就这样:

let something = (a , b ,  c = 0 ,  d = 0 ,  e = 0) =>
{console.log(`a is ${a}; b is ${b};c is ${c};d is ${d};e is ${e}`)};`

如果我给函数赋予两个以上的参数,则分别将它们作为一个函数。 如果我想将值传递给“e”变量并跳过预定义的其他变量怎么办?

2 个答案:

答案 0 :(得分:1)

刚刚通过undefined:

let something = (a, b, c = 0, d = 0, e = 0) => {
  console.log(`a is ${a}; b is ${b}; c is ${c}; d is ${d}; e is ${e}`);
};
something(1, 2, undefined, undefined, 3);

您还可以将可选参数包装在一个将被解构的参数中:

let something = (a, b, {c=0, d=0, e=0} = {}) => {
  console.log(`a is ${a}; b is ${b}; c is ${c}; d is ${d}; e is ${e}`);
};
something(1, 2);
something(1, 2, {c: 3});
something(1, 2, {e: 3});

答案 1 :(得分:1)

你可以将params作为一个对象。它有两个好处,首先,你不必担心顺序,你不必将值传递给c或d。

let something = ({a , b ,  c = 0 ,  d = 0 ,  e = 0}) => {
  return `a is ${a}; b is ${b};c is ${c};d is ${d};e is ${e}`;
}
console.log(something({a: 12 , b: 13, e: 51})); //"a is 12; b is 13;c is 0;d is 0;e is 51"