问题
I recently came across this nifty piece of JavaScript
and I am struggling a bit to understand how it works, and specifically this part :
Array.from(e.attributes, ({name, value}) => [name, value])
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.
What I don't quite get is the way the argument of the function is defined as the litteral object {name, value}
.
I was able to isolate the behavior :
> 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 ?
回答1:
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);
回答2:
What I don't quite get is the way the argument of the function is defined as the litteral object {name, value}.
This is called destructuring assignment JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
回答3:
Your not exactly defining an object literal as an argument, but rather you are destructuring the object. You can think of deconstruction as another way of accessing the properties of an object.
For example, if you have an object a
:
const a = {
name: 'foo',
value: 'bar'
}
You can get its properties in a number of different ways:
Through bracket notation:
const name = a["name"];
const value = a["value"];
Via dot notation:
const name = a.name;
const value = a.value;
Or via destructuring assignment:
const {name, value} = a; // name & value are variables which you can use
const a = {
name: "foo",
value: "bar"
}
var name = a["name"];
var value = a["value"];
console.log(name, value);
var name = a.name;
var value = a.value;
console.log(name, value);
var {name, value} = a;
console.log(name, value);
Thus, when you use {name, value}
in your function arguments, you are effectively telling javascript to extract the name
and value
properties from the object passed in as the argument.
来源:https://stackoverflow.com/questions/54501600/defining-a-function-to-apply-only-to-a-subset-of-properties-of-the-objects-passe