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?
光陰似箭催人老,日月如移越少年。
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.
[1,1,1,1,4,1].reduce(function (a,b) {
console.log(a,b, a === b);
// 返回后一個(gè)元素
return b;
})
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:
const arr = [1, 2, 3, 5, 6, 6 , 7];
let has = false;
for(let i = 0; i < arr.length; i++) {
if (arr.indexOf(arr[i]) !== i) {
has = true;
break;
}
};
if (has) {
console.log('x');
} else {
console.log('y');
}
If ES6 is supported, you can use Set to deduplicate the array, and then determine the length of the two arrays:
const arr = [1, 2, 3, 5, 6, 6, 7];
const arr1 = Array.from(new Set(arr));
console.log(arr.length === arr1.length);
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.
// 比較方式可控
if (arr.some(el => el !== arr[0])) {
x()
} else {
y()
}
// 比較方式不可控,不支持對(duì)象比較,無(wú)論如何都會(huì)遍歷完數(shù)組
if (new Set(arr).size > 1) {
x()
} else {
y()
}
// 比較方式可控,啰嗦但效率快
for (var i = 1; i < arr.length; i += 1) {
if (arr[i] !== arr[0]) {
x()
break
}
}
if (i < arr.length) {
y()
}