I'm trying to learn JavaScript. I came across the following statement:
hero.powers = [...form.powers].filter(box => box.checked).map(box => box.value);
I'm wondering the "box" is apparently referring to a checkbox in the HTML page:
How does this work?
To understand this we can break it down:
[...form.powers]
...
) to create an array from form.powers
(a collection of DOM elements), in this case, it will be an array of checkbox DOM elements. .filter(box => box.checked)
true
from within a .filter
callback (the arrow function) we are telling it to keep the element in the array. Here box
is refering to a given element in the array (as we go through/iterate over the array, box
changes from element to element, or to be more precise, from checkbox to checkbox). .map(box => box.value);
value
of that checkbox. As .map
changes the current iterated item to what it's callback returns. Again, in this case, box
represents the current iterated item, which is a checkbox from our filtered array of checkboxes.So overall:
hero.powers = [...form.powers].filter(box => box.checked).map(box => box.value);
Will set the hero
objects powers
attribute to be an array of the marked checkboxes' values.
See Array.prototype.filter() and Array.prototype.map() for more information on .map()
and .filter()
The form.powers
is probably a node list containing multiple HTML input elements. The spread syntax [...form.powers]
changes the node list into an array, so you are able to map over it. Then you are filtering the newly created array from these inputs, which are not checked, so only these checked remains. Lastly, you are mapping over their values, so you will receive an array of strings, depends what values were written in these inputs.
In a brief:
[...form.powers]
- spread syntax changes a node list into an array .filter(...)
- get rid of non-checked inputs .map(...)
- get an array containing the values of checked inputs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.