简体   繁体   中英

How to access Javascript array with dynamic variable string

When a user selects a radio button, its ID is used to access a javascript array via jQuery's .change() function, and then a $.each function to loop through the contents and unhide form controls. However, when I run this code I get:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in programmer

**Other solutions on stackoverflow that mention this error seem to reference JSON objects, not just normal javascript arrays. I did get this code to work by incorporating an IF statement asking if the variable is "programmer" and then executing code based on that. This is not efficient in my opinion, but it did allow me to then use the actual word "programmer" instead of the dynamic variable name "position" (which would contain programmer).

Radio buttons

<label for="position">Position</label>

Programmer
...

The array:

var programmer = [  
    "blah1", 
    "blah2", 
    "blah3"
];

.change() code

$(".positionRadios").change(function() {
    var position = $(this).attr('id'); 
    if (position != null) { 
        $.each(position, function (index, value) {
            $("#" + value).show();
        });
    } else {
        $('.system').hide();
    }
});

When I tried this with a for loop, it just looped through each letter of the id string. It is not associating the string with the variable array name.

Solutions?

Everything I found online cited the use of parsing JSON to get the variable string to be seen as an object. In this post , I found that the use of eval(), although discouraged, actually rendered the string as an object/array. The code works now without errors. I will continue to research the JSON option.

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