简体   繁体   English

检查数组中的所有元素是否相等

[英]check if all the elements in the array are equal

So i was making a function to check if the elements in an array are equal and if so return true, or false if they arent.所以我正在制作一个函数来检查数组中的元素是否相等,如果相等则返回true,如果它们不相等则返回false。 And I ended up with:我最终得到了:

var uni;

function isUniform(uni) {
    // capture first number of array
    var base = uni[0];
    // check if next numbers are equal to first number
    for (var i = 0; i < uni.length; i++ ) {
        if(uni[i] !== base){
            return false;
        }
        else{return true;} }

}

my problem was that no matter what array I enter to the function it will always return true.我的问题是,无论我输入什么数组到函数中,它总是会返回 true。 after some experimentation I ended up putting the return true outside the loop and it finally worked.经过一些实验,我最终将 return true 放在循环之外,它终于起作用了。

var uni;

function isUniform(uni) {
    // capture first number of array
    var base = uni[0];

    // check if next numbers are equal to first number
    for (var i = 0; i < uni.length; i++ ) {
        if(uni[i] !== base){
            return false;
        }}
    return true;


}

So my question is: why do I need to put the "return true" outside the for loop for the function to work?.所以我的问题是:为什么我需要将“return true”放在 for 循环之外才能使函数工作? I think that I know the reason but I would like an explanation to be clear on that.我想我知道原因,但我想要一个解释清楚。

When the interpreter runs across a return , it immediately terminates the current function - not just the current running block.当解释器遇到return ,它会立即终止当前函数——而不仅仅是当前正在运行的块。 So, in your first snippet, the first matching element will result in return true - isUniform will only result in false if every element is different and you start comparing from the second element instead of starting from the first (because arr[0] === arr[0] is always true except when arr[0] is NaN or similarly strange, such as a reference to a getter)所以,在你的第一个片段,第一个匹配的元素将导致return true - isUniform只会造成false ,如果每个元素都是不同的你开始从第二个元素比较,而不是从第一个开始(因为arr[0] === arr[0]始终为真,除非arr[0]为 NaN 或类似的奇怪,例如对 getter 的引用)

But it would be easier to write your function as follows:但是按如下方式编写函数会更容易:

 const isUniform = (input) => { const base = input[0]; return input.every(element => element === base); } console.log(isUniform([0, 1, 2])); console.log(isUniform([0, 0, 0]));

Suppose you have the following:假设您有以下内容:

[0,0,1]

The first two elements are the same, which will cause return true to execute.前两个元素相同,这将导致return true执行。 return terminates the function and thus the loop, and therefore the last entry (which is different), never even gets compared! return终止函数,从而终止循环,因此最后一个条目(不同的)甚至永远不会被比较!

See for yourself how the following loop only executes once:亲自看看以下循环如何只执行一次:

 const loop = function () { for(let i=1; i<100000; i++) { console.log("I looped " + i + " time") return true } } loop()

Outside of the loop you are setting base equal to the first item in the list.在循环之外,您将 base 设置为等于列表中的第一项。 Then you are iterating over all the items in the list including the first one.然后您将遍历列表中的所有项目,包括第一个项目。 Therefore, the first iteration is always going to be true since base = uni[0].因此,第一次迭代总是正确的,因为 base = uni[0]。

If you're only dealing with numbers you could try this:如果你只处理数字,你可以试试这个:

function allNumbersEqual (arr) {
  return Math.min(...arr) === Math.max(...arr);
}

console.log(allNumbersEqual([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]));
// true

console.log(allNumbersEqual([0.1, 0.2, 0.3, 1, 2, 3]));
// false

Why do it in O(n) when you can do it in O(n*2)?既然可以在 O(n*2) 中完成,为什么要在 O(n) 中完成? :D :D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM