在 Jquery 循环中的数组的下拉列表中附加和选择选项

Appending and Selecting option in dropdown from an Array in loop in Jquery

基本上,我的 table 中有一个下拉菜单。传递字符串后,我想将新行附加到 table。 将新行添加到 table 后,我想 select 每次迭代时下拉列表中的选项。

Jquery代码:

    array1=['A1','B1','C1'];
    for (i=0;i<array1.length;i++) 
    {
    let newrow = $("<tr>")
    let newcol = $("<td>" +
    "<select class='testdrp'>" + 
    "<option value='1' >AAAA</option>" +
    "<option value='2' >BBBB</option>"+
    "<option value='3' >CCCC</option> </select></td></tr>");
    newrow.append(newcol);
    $("tbody.tablename").append(newrow);

#condition to select option from the dropdown    
            if(array1[i]=='A1') {
                                $(".testdrp option[value='1']").attr("selected", true);
                                }
            else if(array1[i]=='B1') {
                                $(".testdrp option[value='2']").attr("selected", true);
                                }
            else               {
                                $(".testdrp option[value='3']").attr("selected", true);
                              }
    }

但是,我无法 select 每行的正确值。 有什么正确的方法可以在这里实现同样的目标吗?

使用newrow.find('select')定位循环中的当前

const vals = {
  A1: 1,
  B1: 2,
  C1: 3
},
array1 = ['A1', 'B1', 'C1'];

for (let i = 0; i < array1.length; i++) {
  let newrow = $("<tr>")
  let newcol = $("<td>" +
    "<select class='testdrp'>" +
    "<option value='1' >AAAA</option>" +
    "<option value='2' >BBBB</option>" +
    "<option value='3' >CCCC</option> </select></td></tr>");
  newrow.append(newcol);
  newrow.find('select.testdrp').val(vals[array1[i]])

  $("tbody.tablename").append(newrow);

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody class="tablename"></tbody>
</table>