有没有一种方法可以将规则同时应用于函数的所有参数? 让我们考虑一个具有5个参数的JavaScript函数。我想从所有参数中删除所有空格 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参数,然后修剪数组中的每个参数:有没有一种方法可以将规则同时应用于函数的所有参数? 让我们考虑一个具有5个参数的JavaScript函数。我想从所有参数中删除所有空格 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(); };,javascript,node.js,Javascript,Node.js,有没有更好的方法来执行此操作,而不是单独修剪每个参数?我会使用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(
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
};