Domanda

In PHP, I can do something like:

$name = "options{$a}"; // or "options" . $a, doesn't matter

for ($i = 0; $i < count($name[$i]); $i++) {
    // do something...
}

as long as options0 exists (assuming $a is 0, or 1, or whatever), this construction is perfectly valid, but... now I need to do the same in Javascript, but without success for now.

Can anyone tell me how can it be done?

Nessuna soluzione corretta

Altri suggerimenti

You can use arrays as some of the comments have described, or you can use object properties. They involve similar notation, but work differently. For instance, you could do something like this:

var options = { option0 : ['a', 'b', 'c'],
                option1 : ['d', 'e'],
                ...
               };
var a = 0;
var count = options['option' + a].length; // assigns 3 to count

This access the property of options named 'option' + a (or, with this sample code, option0).

While you can easily compute and use property names, you cannot (as also pointed out in the comments) do this with local variable names.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top