开发者

How to update a variable inside another variable and have both reflect the change using JavaScript?

开发者 https://www.devze.com 2023-03-07 11:54 出处:网络
I am extremely new to JavaScript and have run into a problem with my code: var ImgNumber =1; var ImgSelect = \'#gallery img:nth-of-type(\' +ImgNumber+ \')\';

I am extremely new to JavaScript and have run into a problem with my code:

var ImgNumber =1;

var ImgSelect = '#gallery img:nth-of-type(' +ImgNumber+ ')';
开发者_StackOverflow
    while (ImgNumber!=4) {
        ImgNumber++;    
        console.log(ImgSelect);
    };

What I would like to happen is for the readout to say

#gallery img:nth-of-type(1)
#gallery img:nth-of-type(2)
#gallery img:nth-of-type(3)

But what happens is

#gallery img:nth-of-type(1)
#gallery img:nth-of-type(1)
#gallery img:nth-of-type(1)

So is there a way to update ImgSelect to reflect the change in ImgNumber?


This line:

var ImgSelect = '#gallery img:nth-of-type(' +ImgNumber+ ')';

what is doing is assigning the value of "#gallery img:nth-of-type(1)" to the variable ImgSelect, so the number won't change inside the string so easily.

But what you can do is a new function to achieve this:

var ImgSelect = function(ImgNumber){
     return '#gallery img:nth-of-type(' +ImgNumber+ ')';
}

To Use the function:

while (ImgNumber!=4) {
    ImgNumber++;    
    console.log(ImgSelect(ImgNumber));
};

Or you can use a function like this, due to that the variable ImgNumber is a global one:

var ImgSelect = function(){
     return '#gallery img:nth-of-type(' +ImgNumber+ ')';
}

To Use the function:

while (ImgNumber!=4) {
    ImgNumber++;    
    console.log(ImgSelect());
};


Put the assignment of ImgSelect within your while loop, otherwise it won't be updated:

var ImgSelect, ImgNumber =1;

while (ImgNumber!=4) {
    ImgNumber++;    
    ImgSelect = '#gallery img:nth-of-type(' +ImgNumber+ ')';
    console.log(ImgSelect);
};


What you're trying to do is not correct, since you have already defined the variable. Once you define it, you have to assign it to something else before it can become anything else. Otherwise it will not change. So, you would have to put the assignment inside the loop.

But what you're really trying to do here should be done with a for loop. It's made for this kind of incremental processing:

for (i = 1; i < 4; i++) {
    console.log('#gallery img:nth-of-type(' + i + ')');
}

Basically, this says, "Starting at 1, keep increasing i until it's less than 4, and each time do what's inside the { }."


An option would be to create a function:

function ImgSelect(ImgNumber) {
    return '#gallery img:nth-of-type(' + ImgNumber + ')';
}

Then call the function in the loop:

while (ImgNumber != 4) {
    console.log(ImgSelect(ImgNumber++));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消