代码之家  ›  专栏  ›  技术社区  ›  DooDoo

jquery将值字符串转换为数组

  •  0
  • DooDoo  · 技术社区  · 6 年前

    请考虑此字符串:

    ['2012-2','2012-3','2012-4','2013-1','2013-2','2013-3','2013-4','2014-1']
    

    我从一个web方法返回这个字符串,我想循环这个值,然后写下:

    var tr = '<tr><td>Title</td>';
    $.each(arrPeriods, function (index, value) {
         tr += '<td>' + value + '</td>';
    });
    tr += '</tr>';
    

    我得到这个错误:

    javascript运行时错误:“in”的操作数无效:应为对象

    我认为问题在于我应该将字符串转换为数组,但我不知道如何才能做到这一点。请帮我解决我的问题。

    3 回复  |  直到 6 年前
        1
  •  1
  •   Brank Victoria    6 年前

    你必须把你所有的 "'" "\"" 然后可以使用json.parse()将字符串转换为数组。就像这样:

    var answer = "['2012-2','2012-3','2012-4','2013-1','2013-2','2013-3','2013-4','2014-1']";
    answer = answer.split("'").join("\"");
    
    var arrPeriods = JSON.parse(answer);
    
    var tr = $('<tr><td>Title</td></tr>');
    
    $.each(arrPeriods, function(index, value) {
      tr.append('<td>' + value + '</td>');
    });
    
    $('table').append(tr);
    
        2
  •  1
  •   Zakaria Acharki    6 年前

    必须使用jquery方法 .append() 取而代之的是添加 td 将字符串转换为数组后。

    注意:如果可能的话,我建议从后端返回一个数组,这样效率会更高。这个解决方案只是暂时的解决方案

    var arrPeriods = "['2012-2', '2012-3', '2012-4', '2013-1', '2013-2', '2013-3', '2013-4', '2014-1']";
    var myArray = arrPeriods.replace(/\[|\]|'/g, '').split(',');
    
    var tr = $('<tr><td>Title</td></tr>');
    
    $.each(myArray, function(index, value) {
      tr.append('<td>' + value + '</td>');
    });
    
    $('table').append(tr);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <table border=1></table>
        3
  •  -1
  •   b00t    6 年前

    查看注释。

    var arrPeriods = "['2012-2', '2012-3', '2012-4', '2013-1', '2013-2', '2013-3', '2013-4', '2014-1']";
    arrPeriods = arrPeriods.replace(/'/g, '"'); // Clean the string into an acceptable JSON string
    arrPeriods = JSON.parse(arrPeriods); // Parse the JSON string
    
    var $tr = $('<tr><td>Title</td></tr>'); // Create the row
    var $table = $('<table></table>')
      .append($tr);
    
    // No need to use jQuery's .each
    arrPeriods.forEach(function (date) {
      $tr.append('<td>' + date + '</td>');
    });
    
    $('body').append($table);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>