【问题标题】:Fill array inside each loop jquery在每个循环jquery中填充数组
【发布时间】:2018-11-21 19:11:01
【问题描述】:

我想从每个循环内创建的数组中获取值

var arr = [];

$.each([52, 97], function(index, value) {

    var arr = [value];

});

console.log(arr);

但是记录的数组没有条目。

【问题讨论】:

  • 尝试使用 .pus() 方法将元素添加到您的数组中

标签: jquery each


【解决方案1】:

你做的错误是var arr = [ value];重新初始化变量,测试一下:

var arr =[];
$.each([ 52, 97 ], function( index, value ) {
 arr.push(value);
});
console.log(arr);

【讨论】:

    【解决方案2】:

    你所做的错误是var arr = [ value]; reinitialized variable & wrong setting of array index.

    var arr = [];
    
    $.each([52, 97], function(index, value) {
    
      arr[index] = value;
    
    });
    
    console.log(arr);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    您也可以使用push() 来执行此操作,就像其他答案(@Boris Bresciani)一样。

    【讨论】:

      【解决方案3】:

      您可以简单地使用 spread syntax 来复制数组元素而无需引用。这意味着您可以独立更改任何数组的内容,而不会影响其他数组的内容。

      var arr1 = [ 52, 97 ];
      var res = [...arr1];
      console.log(res);

      【讨论】:

        【解决方案4】:

        您在函数内部的变量arr 与外部变量arr 不同,而是函数的局部变量。要解决这个问题,不要创建新的局部变量,而是让函数引用外部变量(这称为闭包)。这应该有效:

        var arr =[];
        $.each([ 52, 97 ], function( index, value ) { 
          arr.push(value); 
        });
        console.log(arr);
        

        【讨论】:

          【解决方案5】:

          使用js中的每个循环在Array中添加值

          var ProductTypeId = [];
          $("input[name=ProductTypeId]").each(function() {
              if ($(this).prop('checked') == true) {
                  ProductTypeId.push($(this).val());
              }
          });
          alert(ProductTypeId`enter code here`);
          <input type="checkbox" class="custom-control-input" name="ProductTypeId" id="<?php echo $term['productTypeId']; ?>"  value="<?php echo $term['productTypeId']; ?>">

          【讨论】:

            猜你喜欢
            • 2015-02-04
            • 1970-01-01
            • 2020-02-18
            • 2012-04-16
            • 2020-09-11
            • 2021-04-21
            • 2013-07-18
            • 1970-01-01
            相关资源
            最近更新 更多