定义仅适用于作为参数传递的对象的属性子集的函数 [英] Defining a function to apply only to a subset of properties of the objects passed as argument

查看:64
本文介绍了定义仅适用于作为参数传递的对象的属性子集的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了这个漂亮的JavaScript

我正在努力了解它的工作原理,特别是这部分:

and I am struggling a bit to understand how it works, and specifically this part :

  Array.from(e.attributes, ({name, value}) => [name, value])

在这里,我们处理 NamedNodeMap Attr对象的集合,并且Attr确实具有名为namevalue的属性. 因此,我们有一个匿名函数,该函数接受一个对象并返回一个数组.到目前为止,一切都很好.

Here, we deal with a NamedNodeMap which is a collection of Attr objects, and an Attr does have properties named name and value among many others. So, we have an anonymous function that takes an object and returns an array. So far, so good.

我不太了解该函数的参数定义为垃圾对象{name, value}的方式.

What I don't quite get is the way the argument of the function is defined as the litteral object {name, value}.

我能够隔离这种行为:

> o={ a: 1, b: 2, ldfk: 'mùl' }
> let objToArr = function({a,b}){ return [a,b] }

> objToArr(o)
[ 1, 2 ]
> 
> o = {'dfklj':3.14, 'c':'z', 'a':1, 'foo':'bar', 'b':2, 'z':26 }
{ dfklj: 3.14, c: 'z', a: 1, foo: 'bar', b: 2, z: 26 }
> objToArr(o)
[ 1, 2 ]
> 

但是我仍然不明白为什么为什么.有人可以解释一下或将我推荐给适当的文档吗?

but I still don't understand why it works. Could someone please explain or refer me to the appropriate documentation ?

推荐答案

您正在寻找的是

What you are looking for is a destructuring assignment, where an object is assigned to an object literal with only the keys, you need to take.

var object = { name_: 'foo', value: 42 },
    { name_, value } = object;           // name is a property of window

console.log(name_);
console.log(value);

这篇关于定义仅适用于作为参数传递的对象的属性子集的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆