问题
I am having a hard time fully understanding how this code works. This is just form validation code copy and pasted from bootstrap.
My issue starts with this line var validation = Array.prototype.filter.call(forms, function(form)
It seems to me it is creating an array called validation containing any element with the class name "needs-validation". Then is it calling the anonymous function and passing in the entire form and running the subsequent lines of code
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
on each of the elements that contain the class name "needs-validation"?
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
This code successfully validates the inputs on a form. I just don't understand how it works.
回答1:
The method document.getElementsByClassName return a HTMLCollection, in first look it similar to Array but HTMLCollection doesn't has methods .filter, .map, reduce, etc.
So for using these methods, we need to convert HTMLCollection to an array.
Or we can use, specific of javascript: Array.prototype.filter go by iterable on an object, and if you look in details on HTMLCollection what document.getElementsByClassName returns it has keys and it's iterable. So we can call method Array.prototype.filter.call( and pass as a context (first parameter) our HTMLCollection, second parameter will be a functions what will be calls for each element in collection.
Little bit more about call() method https://gomakethings.com/what-the-hell-is-the-call-method-and-when-should-you-use-it/
来源:https://stackoverflow.com/questions/57419277/array-prototype-filter-callforms-functionform-what-is-this-doing