第一个示例中的语法是什么意思?
使用的语法是以下组合默认参数语法 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters and 解构赋值语法 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Unpacking_values_from_a_regular_expression_match
'={}' 部分的意义是什么?
使用默认参数语法 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters: the '= {}'
零件组{}
(一个空对象)作为单个参数的默认值getMovies
让我们分解一下:
在这里,我们设置'flying'
作为默认值power
范围
function giveSuperPower(power='flying'){
console.log(`you have got: "${power}"`);
}
giveSuperPower('infinite energy');
// you have got: "infinite energy"
giveSuperPower();
// you have got: "flying"
如果参数是一个对象怎么办?
function giveSuperPower(power){
console.log(`you have got: "${power.name||'flying'}"`);
console.log(`it last for ${power.duration||'∞'}min`);
}
giveSuperPower({name: 'strength', duration: 5 });
// you have got: "strength"
// it last for 5min
看起来不错..对吧?
咱们试试吧
giveSuperPower();
// Uncaught ReferenceError: power is not defined
好吧,这是一个问题。
让我们设置一个默认参数值(一个空对象)
function giveSuperPower(power={}){
console.log(`you have got: "${power.name||'flying'}"`);
console.log(`it last for ${power.duration||'∞'}min`);
}
giveSuperPower();
//you have got: "flying"
//it last for ∞min
让我们解构权力power
范围
function giveSuperPower({name, length} = {}){
console.log(`you have got: "${name||'flying'}"`);
console.log(`it last for ${duration||'∞'}min`);
}
让我们设置默认参数值name
and length
function giveSuperPower({name = 'flying', length = '∞'} = {}){
console.log(`you have got: "${name}"`);
console.log(`it last for ${duration}min`);
}
就是这样 :)