Domanda

So, I'm having trouble keeping a value from a function.

var A4 = 0;
var A1 = 1;
var A2 = 2;
var A3 = 3;
var ROW1 = [A1, A2, A3, A4];
function contains(a, obj) { 
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
       }
    }
    return false;
}

The accepted value of this function when used with the given variables is 4.

var InRow = function(cell, row) {
    cell = 1;
    if (contains(row, cell)) {
        cell = 2;
        if (contains(row, cell)) {
            cell = 3;
            if (contains(row, cell)) {
                cell = 4;
                if (contains(row, cell)) {
                    return false;
                } else {
                    cell = 4;
                }
            } else {
                cell = 3;
            }
        } else {
            cell = 2;
        }
} else {
    cell = 1;
    }
    console.log(cell)

That console.log gives the accepted value, four.

};
InRow(A4, ROW1);
console.log(A4);

However, this one gives a value of 0, no matter what.

I am wondering if there is any way to store the value from the second function to use later? i.e., make the second console.log return 4.

È stato utile?

Soluzione

Can't you just return the value? Or am I missing something?

var InRow = function(cell, row) {
    cell = 1;
    if (contains(row, cell)) {
        cell = 2;
        if (contains(row, cell)) {
            cell = 3;
            if (contains(row, cell)) {
                cell = 4;
                if (contains(row, cell)) {
                    return false;
                } else {
                    cell = 4;
                }
            } else {
                cell = 3;
            }
        } else {
            cell = 2;
        }
    } else {
        cell = 1;
    }
    return cell;
}

And then :

var cell = InRow(A4, ROW1);
console.log(cell);

Also what is the point of passing in A4 into the function and then overwriting it with a value of 1? You can rewrite the whole thing to this and it will have the same effect.

var InRow = function(row) {
    var cell = 1;
    if (contains(row, cell)) {
        cell = 2;
        if (contains(row, cell)) {
            cell = 3;
            if (contains(row, cell)) {
                cell = 4;
                if (contains(row, cell)) {
                    return false;
                } else {
                    cell = 4;
                }
            } else {
                cell = 3;
            }
        } else {
            cell = 2;
        }
    } else {
        cell = 1;
    }
    return cell;
}

var cell = InRow(ROW1);
console.log(cell);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top