Member-only story
Have you really avoided the hidden trap of JavaScript array method every?
In the process of learning JavaScript,Array.prototype.every
This method may be one of the tools you frequently use. According to the description of MDN, this method is used to test whether all elements in the array have passed the provided test function and return a Boolean value. At first glance, this method appears to be very simple and easy to use, but if not careful, you may encounter some hidden pitfalls.
Simple usage scenarios
The concept of “vacuum truth” originates from mathematics and refers to the assumption that a condition is satisfied when there are no possible validation objects (such as an empty array without elements). In other words, if there are no counterexamples, we assume that all conditions hold.
stayevery
In the specific implementation of the method, callback functions are used to test the conditions of each array element. If the array is empty, the callback function will not execute at all because there are no elements to call it. In this case, JavaScript defaults to all "elements" meeting the conditions, thereforeevery
returntrue
。
Re understandevery
We usually believe thatevery
It is checking whether each element in the array satisfies a certain condition. But in reality, a more…