【问题标题】:Pushing arrays based on each row inputs dynamically基于每行输入动态推送数组
【发布时间】:2018-08-18 18:58:15
【问题描述】:

根据我的代码,我想将每一行的输入推送到每个数组。如果是第 1 行,它应该将第 1 行的所有输入值推送到数组a1。第二行的输入应该被推送到数组a2 等等。

这主要是为了我的代码的性能优化,因为我的真实代码的行数是 20+,我正在尝试像下面这样但没有成功。

我希望能够知道每一行的数据(用于验证目的)

$('#check').click(function(event){
event.preventdefault;
  var a1=[];var a2=[];
  $("[id^=row]").find("td input").each(function(i) { a[i].push(this.value); });
  $('#output').html('<h4>Pushed arrays:</h4>a1: ['+a1 +'] <br/> a2: ['+a2+']');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr id="row1">
        <td>1</td>
        <td><input  type="text" value="0" size="4"></td>
        <td><input  type="text" size="4"></td>
        <td><input  type="text" size="4"></td>
        <td><input  type="text" value="0" size="4"></td>
    </tr>
    <tr id="row2">
        <td>1</td>
        <td><input  type="text" size="4"></td>
        <td><input  type="text" value="1" size="4"></td>
        <td><input  type="text" value="0" size="4"></td>
        <td><input  type="text" size="4"></td>
    </tr>
</table>
<button id="check">Check Values</button>
<div id="output"></div>

【问题讨论】:

  • 你有一些代码错误:这一行的第一个你忘了关闭字符串表达式,应该是这样的:$('#output').html('&lt;h4&gt;Pushed arrays:&lt;/h4&gt;a1: ['+a1 +'] &lt;br/&gt; a2: ['+a2+']'); 和第二个你不能做a[i] 并期望它找到一个a2a1 的变量,相反它将尝试在位置 i 处查看变量 a。你可以这样做:[`a${[i]}`].push(this.value);

标签: javascript jquery arrays performance optimization


【解决方案1】:

我会这样做:

$("#check").click(function() {
  // collect data
  var rows = $("tr").get().map(r => (
    $("input", r).get().map(i => i.value)
  ));
  // print data
  $("#output").html("<h4>Pushed arrays:</h4>" + rows.map((r, i) => (
    "a" + (i + 1) + ": [" + r.join(", ") + "]"
  )).join("<br>"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr id="row1">
    <td>1</td>
    <td><input type="text" value="0" size="4"></td>
    <td><input type="text" size="4"></td>
    <td><input type="text" size="4"></td>
    <td><input type="text" value="0" size="4"></td>
  </tr>
  <tr id="row2">
    <td>2</td>
    <td><input type="text" size="4"></td>
    <td><input type="text" value="1" size="4"></td>
    <td><input type="text" value="0" size="4"></td>
    <td><input type="text" size="4"></td>
  </tr>
</table>
<button id="check">Check Values</button>
<div id="output"></div>

理解上述代码的提示

JQuery API 和 MDN 文档:

joinmap 和箭头函数的演示:

xs = ["A", "B", "C"]
// ["A", "B", "C"]
"[" + xs.join(", ") + "]"
// "[A, B, C]"
xs.map(function (x) { return parseInt(x, 16); })
// [10, 11, 12]
xs.map(x => parseInt(x, 16))
// [10, 11, 12]
xs.map((x, i) => x + i)
// ["A0", "B1", "C2"]
xxs = [["A", "B"], ["C", "D"]]
// [["A", "B"], ["C", "D"]]
xxs.map(xs => "[" + xs.join(", ") + "]")
// ["[A, B]", "[C, D]"]
xxs.map(xs => "[" + xs.join(", ") + "]").join("<br>")
// "[A, B]<br>[C, D]"

【讨论】:

  • 您刚刚将35+ 行代码转换为2 恭喜。我需要研究它是如何工作的,因为它只有 2 行但理解起来要复杂得多:)
  • 如何将每一行的数据存储到一个变量中? (主要是把那个变量解析成php)
  • @GragasIncoming 答案已更新。逐行解释代码太长了,但我相信一些提示也会有所帮助。您可以使用 JSON 格式将数据发送到 PHP,请参阅 JSON.stringify() (JS) 和 json_decode() (PHP)。
  • @GragasIncoming 顺便说一句,尽管听起来令人惊讶,但我的目标不是让代码简短,我的目标是让它可读。当你不熟悉某件事时,并不意味着它天生就很难理解:-P 熟悉map,你将永远不会回头;-)
【解决方案2】:

我想你是这个意思。

我尽量靠近你的代码,以免吓跑 JavaScript

$('#check').click(function(event){
  event.preventdefault;
  var a=[];
  $("[id^=row]").each(function() { // for each row
    var idx = a.length; // find how many entries in a
    a[idx]=[]; // add a new array
    $(this).find("td input").each(function(i) { a[idx].push(this.value); }); // fill the array
  });  

  var output = ""; // initialise a string
  for (var i=0;i<a.length;i++) { // loop over a's items
    output += "a["+i+"]:"+a[i].join(","); // join each array with comma
    output += "<br/>";
  }  
  $('#output').html('<h4>Pushed arrays:</h4>'+output);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr id="row1">
        <td>1</td>
        <td><input  type="text" value="0" size="4"></td>
        <td><input  type="text" size="4"></td>
        <td><input  type="text" size="4"></td>
        <td><input  type="text" value="0" size="4"></td>
    </tr>
    <tr id="row2">
        <td>1</td>
        <td><input  type="text" size="4"></td>
        <td><input  type="text" value="1" size="4"></td>
        <td><input  type="text" value="0" size="4"></td>
        <td><input  type="text" size="4"></td>
    </tr>
</table>
<button id="check">Check Values</button>
<div id="output"></div>

【讨论】:

    【解决方案3】:

    我会使用$.map 创建一个嵌套数组。好像你想要有很多行。因此,我建议使用 2d 数组而不是单个变量,以避免重复代码。使用二维数组,您可以遍历每一行;对于单个变量,您必须为每一行手动重写相同的代码。

    $('#check').click(function(event){
      event.preventdefault;
      var serialize = [];
      $("#myTable tr").each(function () {
        serialize.push($.map($(this).find("input"), function (ele) {
          return ele.value;
        }));
      });
      console.log(serialize);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table id="myTable">
    <tr>
              <td>1</td>
             <td><input  type="text" value="0" size="4"></td>
             <td><input  type="text" size="4"></td>
             <td><input  type="text" size="4"></td>
             <td><input  type="text" value="0" size="4"></td>
            </tr>
    <tr>
              <td>1</td>
             <td><input  type="text" size="4"></td>
             <td><input  type="text" value="1" size="4"></td>
             <td><input  type="text" value="0" size="4"></td>
             <td><input  type="text" size="4"></td>
            </tr>
           </table>
    <button id="check">Check Values</button>
    <div id="output"></div>

    【讨论】:

    • 好的,我需要分别对每一行的输入进行验证
    • @GragasIncoming 如果更容易将其分成单独的变量,只需执行var a1 = serialize[0], a2 = serialize[1]
    • 什么都不为空且值为 1 或 0 时我应该如何编辑?
    • @GragasIncoming 我对你的措辞有点困惑。它将每列中的任何内容添加到数组中。它将添加文本框内的任何内容。
    • 好吧,还有一个问题。我需要将每个数组转换为字符串,可以这样做serialize[2].join(""); 吗?
    猜你喜欢
    • 1970-01-01
    • 2017-03-06
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 2019-11-21
    相关资源
    最近更新 更多