[英]Destructuring Assignment to Pass an Object as a Function's Parameters in Javascript behaviour
In a course, I use destructuring:在课程中,我使用解构:
const stats = {
max: 56.78,
standard_deviation: 4.34,
median: 34.54,
mode: 23.87,
min: -0.75,
average: 35.85
};
const half = ({min, max}) => (max + min) / 2.0;
I first thought the right syntax would be (which also works):我首先认为正确的语法是(这也有效):
const half = ({min, max} = stats) => (max + min) / 2.0;
My question is how JS knows in which object to look for min
and max
and what would happen in the event of another object stats2
having properties min
and max
as well?我的问题是 JS 如何知道在哪个 object 中查找
min
和max
,以及如果另一个 object stats2
具有属性min
和max
会发生什么? I don't understand the behaviour of the code in that case.在这种情况下,我不理解代码的行为。
When you call the method half
you are writing like this,当你调用
half
的方法时,你是这样写的,
half(stats);
So, JS knows the object you passed for half method.因此,JS 知道您为 half 方法传递的 object。 Therefore js will look for min, max keys in the passed object if you declare the half method like this,
因此,如果您声明这样的 half 方法,js 将在传递的 object 中查找最小、最大键,
const half = ({min, max}) => (max + min) / 2.0;
For another object stats2, you would again call the half method the following way,对于另一个 object stats2,您将再次按以下方式调用 half 方法,
half(stats2);
Lets say you have 2 params for half method like,假设您有 2 个用于 half 方法的参数,例如,
const half = ({min, max}, {foo,bar}) => (max + min) / 2.0;
Now if you call the half method with both your stats and stats2 object,现在,如果您使用 stats 和 stats2 object 调用 half 方法,
half(stats, stats2);
It will first take the min and max from stats and try to find foo and bar
from stats2.它将首先从 stats 中获取 min 和 max 并尝试从 stats2 中找到
foo and bar
。
half
is an arrow function. half
是箭头 function。 Now, to use half
that you defined, you would need to pass an object like that half(myObject)
.现在,要使用您定义的
half
,您需要像half(myObject)
一样传递 object 。 When half
receives this myObject
it takes the min
and max
values out of it.当
half
收到这个myObject
时,它会从中取出min
和max
。 If the provided object does not contain these values, then it will substitute the missing value with undefined
.如果提供的 object 不包含这些值,那么它将用
undefined
替换缺失的值。
To answer your question, JS will look for min
and max
only in that object that is passed to your half
function.为了回答您的问题,JS 将仅在传递给您的
half
function 的 object 中查找min
和max
。 Therefore, other objects that are defined outside the scope of half
will not be touched.因此,在 scope 的
half
之外定义的其他对象将不会被触及。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.