var i = 0; var test = 'test1_test2' ; var testr = test.split('_'); var test1 = 'tiiiies'; var test2 = 'testtyty2'; while (i < 2) { alert( window[testr[i]]) i++ }; 

why it does not work in the function gives undefined

Closed due to the fact that off-topic participants zRrr , Kromster , cheops , user194374, Streletz Jun 28 '16 at 10:27 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - zRrr, Kromster, cheops, Community Spirit, Streletz
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • Where exactly does not work? In the Chrome console, for example, everything works. - Yaant

1 answer 1

Because you have this code wrapped in something else ( window.onload , $(document).ready , some other function), which makes the scope of your variables not global. Try removing var before test1 and test2 .

 function Test() { var i = 0; var test = 'test1_test2' ; var testr = test.split('_'); test1 = 'tiiiies'; test2 = 'testtyty2'; while (i < 2) { alert( window[testr[i]]); i++; }; } Test();