【发布时间】:2020-03-01 13:56:05
【问题描述】:
假设我有一个有 50 个参数的函数,我需要修改在函数签名中创建的每个命名变量的值。
他只有 4 个参数,而不是 50 个参数:
// Each of these strings are padded with intentional and unnecessary whitespace:
let show = " show ";
let me = " me ";
let the = " the ";
let bunny = " bunny ";
function showMeTheBunny(show, me, the, bunny)
{
// I want to trim each argument, without having to do this:
show = show.trim();
me = me.trim();
the = the.trim();
bunny = bunny.trim();
// The above lines, within this function,
// are the ones I want to replace with a loop (if possible)
return `${show} ${me} ${the} ${bunny}: ????`;
}
console.log(showMeTheBunny(show, me, the, bunny)); // output: "show me the bunny: ????"
arguments 对象可以访问传递给函数的所有参数,但它似乎没有提供更改命名变量本身值的方法。
是否可以通过一个修改每个变量的函数来运行所有命名变量(在函数签名中命名),然后再使用这些修改后的参数(使用相同的变量名)?
【问题讨论】:
-
“假设我有一个有 50 个参数的函数......” 你好!
-
我不明白你所说的
named-variables是什么意思,你能显示一个unnamed-variable吗? -
@LonnieBest:我明白了。通常此类函数有一个签名
sqlExecute(statement, args),如果使用位置占位符,args是一个数组,如果使用命名占位符,则是一个对象。 -
@LonnieBest - 是的。你可以通过使用解构来解决这个问题。例如,假设您接受一个对象:
for (const [name, value] of Object.entries(args)) { args[name] = value.trim(); }后跟const {show, me, the, bunny} = args;。它的优点是您不必担心订单。 -
@LonnieBest:是的,但谁说你必须使用模板?使用您自己的占位符传递一个普通字符串,例如
WHERE {whatever} > 0并即时替换它们。模板在这里是一个错误的工具。
标签: javascript ecmascript-next