简体   繁体   中英

JavaScript: Looping through an array of booleans

I'm looking to loop through an array of booleans that will change based on what link the user clicks on. First, I initialize them...

var boolean1 = false;
var boolean2 = false;
var boolean3 = false;

Next, I have Strings that contain the links to a new page...

var link1 = "index.html";
var link2 = "someotherpage.html";
var link3 = "somepage.html";

Then, I put the values in respective arrays

var booleanArray = new Array(3);
booleanArray[0] = boolean1;
booleanArray[1] = boolean1;
booleanArray[2] = boolean1;

var linkArray = new Array(3);
linkArray[0] = link1;
linkArray[1] = link2;
linkArray[2] = link3;

Then, I have functions that change the values (The values will be called based one what link the user clicks on)...

//onlick...
function changeBoolean1()
{
    boolean1 = true;
}
function changeBoolean2()
{
    boolean2 = true
}
function changeBoolean3() 
{
    boolean3 = true;
}

Finally, based on which method was called onlick , one of the booleans will be set to false . At that point, I want to loop through the array of booleans, and get which one was set to false . Based on which one was false , it's respective link will open.

function getChoice()
{
    for(var i = 0; i < booleanArray.length; i++)
    {
        if(booleanArray[i] == true)
        {
            window.location.href = linkArray[i];
            break;
        }
    }
}

However, the method does not get based the

You need to change you onclick functions to update the array instead of the original variables

//onlick...
function changeBoolean1() {
    booleanArray[0] = true;
}
function changeBoolean2() {
    booleanArray[1] = true
}
function changeBoolean3() {
    booleanArray[2] = true;
}

Since Booleans are primitives, what gets stored in the actual array is the values and not a reference to your original variable (as you would expect with objects)

primitive type variable like string,number are always pass as pass by value. so you need to set your value explicitly in array or set your boolean property in a object.

function changeBool(booleanArray, index){
     booleanArray[index] = true;
}

function getChoice(){
    for(var i = 0; i < booleanArray.length; ++i){
        if(booleanArray[i]){
            window.location.href = linkArray[i];
            break;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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