简体   繁体   中英

JavaScript arrow function syntax. How does BOX as filter work?

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]

  • Use the spread syntax ( ... ) 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)

  • This statement means go through all the elements in the array we created above, in this case, our elements are checkboxes, and keep only the checkboxes which are checked. As when we return 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);

  • This function will now loop/iterate over the filtered array (ie the array containing boxes which are only checked), and map/change each checkbox within it to the 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM