Arrays和For循环JS的逻辑问题

时间:2018-06-04 13:55:15

标签: javascript arrays for-loop if-statement

我的逻辑或JS的逻辑显然有问题(哈哈) 我真的不明白为什么其中一个有效,另一个没有 这些函数用于检查数组中的每个索引是否相同。第一个工作,第二个不工作,我不知道这两个的逻辑是如何不同的(除了改变位置的明显点)。
1.

function isUniform(x) {
    var first = x[0];
    for(var i = 1; i < x.length; i++) {
        if(first === x[i]) {
            return true;
            i++;
        }
    } return false;
};  

2。

function isUniform(x) {
    var first = x[0];
    for(var i = 1; i < x.length; i++) {
        if(x[i] !== first) {
            return false;
            i++;
        }
    } return true;
};  

使用的数组:isUniform([1,1,1,2])和isUniform([1,1,1,1])

2 个答案:

答案 0 :(得分:2)

一旦你进入for循环,循环停止,函数结束。

在你的第一个例子中,第一个将永远不等于x [i],因为你从1开始,然后是第一个=== x [0],所以循环结束并返回false。

在你的第二个例子中,你总是在i = 1时返回false,因为x [1]!== x [0],所以在第一次检查之后循环总是返回false。

答案 1 :(得分:1)

Here is a breakdown as to how your functions work on a line-by-line level (I've included comments after each statement):

function isUniform(x) {
    var first = x[0]; //SET "FIRST" to first element in array
    for(var i = 1; i < x.length; i++) { //loop from second element to the end
        if(first === x[i]) { //if "FIRST" is equal to this element
            return true; //conclude that the ENTIRE ARRAY is uniform and quit function
            i++; //incremenet "i" (note, the loop automatically does this, so this will result in an extra increment
        }
    } return false; //conclude the array is not uniform IF THE FIRST ITEM IS UNIQUE
}; 

Here is a breakdown of the second function:

function isUniform(x) {
    var first = x[0];//SET "FIRST" to first element in array
    for(var i = 1; i < x.length; i++) { //loop from second element to the end
        if(x[i] !== first) { //if this element is not equal to the first CONCLUDE THAT THE ARRAY IS NOT UNIFORM and quit function
            return false;
            i++; //again, extra un-needed increment, but it technically does not matter in this case
        }
    } return true; //CONCLUDE that since no items were NOT equal to the first item, the array is uniform
};  

Thus, it should now be clear that the second array fulfills your purpose while the first one does not. Really, the first one checks if any elements other than the first are equal to the first.