让我们考虑一个带有5个参数的javascript函数doTruncate。我想从所有论点中删除所有空白。
const doTruncate = function (pre = "", firstName = "", middleName = "", lastName = "", post = "") {
pre = pre.strim()
firstName = firstName.trim()
middleName = middleName.trim()
lastName = lastName.trim()
post = post.trim()
let result = pre + " " + firstName + " " + middleName + " " + lastName + " " + post;
return result.trim();
};
有没有更好的方法来做到这一点,而不是单独修剪每个论点?
我会使用rest参数,然后修剪数组中的每个参数:
const doTruncate = (...args) => {
return args.slice(0, 5) // this slice can be removed if the function
// is always called with 5 or less arguments
.map(str => (str || '').trim()) // the `|| ''` is only needed
// if `undefined` may be explicitly passed
// in the middle of the argument list
// while later arguments are non-empty
.join(' ')
.trim(); // this last trim can be removed
// if the first and last parameters, when passed, aren't empty
};