admin管理员组

文章数量:1279206

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. 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. after some experimentation I ended up putting the return true outside the loop and it finally worked.

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?. I think that I know the reason but I would like an explanation to be clear on that.

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. 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. after some experimentation I ended up putting the return true outside the loop and it finally worked.

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?. I think that I know the reason but I would like an explanation to be clear on that.

Share Improve this question asked Apr 20, 2018 at 23:11 lcrimsonllcrimsonl 631 silver badge8 bronze badges 3
  • Your first snippet says "if the 0th element matches the 0th element, then all the elements are equal" – Patrick Roberts Commented Apr 20, 2018 at 23:13
  • Sort the array. Then if the first and last are equal, they must all be equal. – Barmar Commented Apr 20, 2018 at 23:14
  • 2 @Barmar except that sorting is O(n log(n)) and iterating like this is O(n). It makes more sense to set up this relatively simple logic than to implement more plicated logic that also has the side effect of sorting the input array, which no longer makes it a pure function. – Patrick Roberts Commented Apr 20, 2018 at 23:16
Add a ment  | 

4 Answers 4

Reset to default 12

When the interpreter runs across a return, it immediately terminates the current function - not just the current running block. 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 paring 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)

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 terminates the function and thus the loop, and therefore the last entry (which is different), never even gets pared!

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. 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].

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)? :D

本文标签: javascriptcheck if all the elements in the array are equalStack Overflow