I need to find whether there are different values in the array. If it exists, execute function x. If it does not exist, execute function y. But using a for loop, if it encounters the same thing at first, it will execute y, and it will not execute x until it encounters something different. How to make it traverse all the loops and then execute the corresponding function?
Use Array.prototype.every() or Array.prototype.some()
1. Use the ES5 array.every method, which executes a function on each array element. When all function execution results are true, the final result is true. Otherwise, it will end early and get false.
2. Using a for loop, you need a variable to save the value of the first element of the array, and then start the loop. When you find that there is an element in the array that is not equal to your variable, you can determine that it is time to execute X (this You can break it when); otherwise, there are no different values in the array, execute Y
In fact, method 1 also requires this variable.
3. Use the ES5 array.reduce method, which accepts two array elements at a time. You can directly compare whether the two elements are equal. As long as they are not equal, it is Y.
But this method cannot break
Add a variable before for, change it if you encounter it in for, and then if after for
If you use a for loop, you need to define a variable outside the for as a flag:
If ES6 is supported, you can use Set to deduplicate the array, and then determine the length of the two arrays:
The description of "there are different values" is a bit vague. My understanding is that there is a value in the array that is different from other values.