在React中,我创建了下面提到的函数:
infoPrint (firstname = '--', middlename = '--', surname = '--')
{
console.log('Firstname: ', firstname, ', Middle name: ', middlename, ', Surname: ', surname);
}
我在componentWillMount中调用此函数:
componentWillMount() {
var firstname = 'Naisarg';
var surname = 'Parmar';
this.infoPrint(firstname,surname);
}
我得到以下输出:
Firstname: Naisarg, Middle name: Parmar, Surname: --
但是我期望这个:
Firstname: Naisarg, Middle name: --, Surname: Parmar
答案 0 :(得分:2)
您可以通过传递文字对象作为函数的参数来实现:
class User extends Component {
componentWillMount() {
var firstname = 'Naisarg';
var surname = 'Parmar';
this.infoPrint({ firstname, surname });
}
infoPrint({ firstname = '--', middlename = '--', surname = '--' }) {
console.log('Firstname: ', firstname, ', Middle name: ', middlename, ', Surname: ', surname);
}
}
这是一种非常常见的模式,它对可选参数很有帮助。
-
如果您不想使用对象,则必须以正确的顺序传递所有参数:
class User extends Component {
componentWillMount() {
var firstname = 'Naisarg';
var surname = 'Parmar';
this.infoPrint(firstname, null, surname);
}
infoPrint(firstname = '--', middlename = '--', surname = '--') {
console.log('Firstname: ', firstname, ', Middle name: ', middlename, ', Surname: ', surname);
}
}
答案 1 :(得分:1)
要实现所需的功能,您需要为--
参数传递null
或middlename
:
componentWillMount() {
var firstname = 'Naisarg';
var surname = 'Parmar';
this.infoPrint(firstname, null, surname);
this.infoPrint(firstname, '--', surname);
}
或者,您可以通过对象参数间接传递这些参数来重构方法签名:
function infoPrint(name = { first: '--', middle: '--', last: '--' }) {
console.log('Firstname: ', name.first, ', Middle name: ', name.middle, ', Surname: ', name.last);
}
infoPrint({
first: 'Naisarg',
last: 'Parmar'
});
上面显示的“对象参数”方法通过保留参数本身之间的(键)关系以及在infoPrint()
函数中实际使用每个键参数的方式来解决您面临的问题。
否则,JavaScript运行时将无法知道您打算将surname
变量作为“第三姓参数”实际传递给infoPrint()
-简单地说,您的通过是从头到尾分配的。如下所示将变量替换为值可能会更深入地了解正在发生的事情以及为什么原始代码无法按预期工作:
// var firstname = 'Naisarg';
// var surname = 'Parmar';
// Substitute variables with values to better understand how
// arguments are being passed to the function
this.infoPrint(
'Naisarg' /* <-- firstname */,
'Parmar' /* <-- middlename */,
/* no value for surname, so use default "--" */
); /* Prints: "Firstname: Naisarg , Middle name: Parmar , Surname: -- " */