Function(arguments): 修正输入顺序

huangapple go评论62阅读模式
英文:

Function(arguments): Correcting the order of input

问题

这不是一个代码问题,更像是一个一般性问题。

当你在函数中包括(arguments),或者在对象/构造方法中使用时,它们被传递给函数的顺序很重要。

例如:function(x,y,z) != function (z,y,x),并且根据变量传递的方式,会得到不同的结果/可能会引发错误。

是否有一些我可以写在函数内部的东西,来纠正值的顺序,使其符合函数的期望?

这样,无论是传递 function(z,y,x) 还是 function(y,x,z),函数都会自动纠正为 function(x,y,z)

或者这是良好编程的一个方面,你希望一切都被明确定义,并且绝对,这样你就不必设置像我描述的那种应变措施。

英文:

This isn't a code issue, more of a general question.

When you include (arguments) in functions, or object / constructor methods, the order in which they are passed into the function is important.

example: function(x,y,z) != function (z,y,x) and would give a different result/might cause bugs depending how the variables are passed.

Is there something I can write inside the function to correct the order of the values to what the function expects?

So that it doesn't matter if function(z,y,x) or function(y,x,z) are passed, because function always correct itself to function(x,y,z)

Or is this an aspect of good programming where you want everything to be explicitly defined, & absolute, so you don't have to set up contingencies in the way I described.

答案1

得分: 0

给定一个类似以下的函数:

function f(x, y, z) {
  return x + 2 * y + 3 * z;
}

输入参数是按顺序排列的,因此调用 f(1, 2, 3) 会将 x=1, y=2, z=3 局部绑定到函数作用域内({} 大括号内)。

要实现无序输入参数,需要一种方法来标识参数的位置,可以通过将每个参数与对象中的名称进行映射,并将其传递给函数来实现。

function g(obj) {
  { z, x, y } = obj;
  return x + 2 * y + 3 * z;
}

这样,输入就是无序的,但仍然编码了参数属于哪个位置的信息。

这样 f(1, 2, 3)g({z: 3, y: 2, x: 1})g({x: 1, y: 2, z: 3}) 都会产生相同的结果。

英文:

Given a function like

function f(x,y,z) {
  return x + 2*y + 3*z
}

the input is ordered by so a call f(1,2,3) binds x=1, y=2, z=3 locally inside the function scope ({} braces).
To input arguments without order, there needs to be some kind of way to identify the argument without position, this can be achieved by mapping each argument with a name in an object and passing it to the function.

function g(obj) {
  { z, x, y } = obj
  return x + 2*y + 3*z
}

This way the input is order free, but the information about what argument belongs where is still encoded.

Making f(1,2,3), g({z:3,y:2,x:1}) and g({x:1,y:2,z:3}) give the same result.

huangapple
  • 本文由 发表于 2023年5月22日 21:51:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76306897.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定