javascript - js traversal problem?
大家讲道理
大家讲道理 2017-06-30 09:57:33
0
5
682

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?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(5)
伊谢尔伦

Use Array.prototype.every() or Array.prototype.some()

Ty80

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);
    // 返回后一个元素
    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.

  1. // 比较方式可控
    if (arr.some(el => el !== arr[0])) {
      x()
    } else {
      y()
    }
  2. // 比较方式不可控,不支持对象比较,无论如何都会遍历完数组
    if (new Set(arr).size > 1) {
      x()
    } else {
      y()
    }
  3. // 比较方式可控,啰嗦但效率快
    for (var i = 1; i < arr.length; i += 1) {
      if (arr[i] !== arr[0]) {
        x()
        break
      }
    }
    if (i < arr.length) {
      y()
    }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!