如何使用jquery创建动态关联数组?

时间:2016-12-16 12:22:11

标签: javascript jquery html arrays

我想要这样的数组: -

arr[0][from] = value
arr[0][to] = value

arr[1][from] = value
arr[1][to] = value

。 。 等等。

我输入的数组html元素来自&到现场。

<input type="text" name="from[]" value=""/>
<input type="text" name="to[]" value=""/>

现在,我正在使用以下代码制作数组,并且它在控制台中给出了错误,例如&#34; Uncaught TypeError:无法读取属性&#39; push&#39;未定义&#34;。

    var arr = [];
    $('input[name^=from]').each(function(index,val) {
              var from = $(this).val();
              if(typeof arr[index] === undefined)
                arr[index] = [];

             arr[index].push({from:from});  
    });
    $('input[name^=to]').each(function(index,val) {
              var to= $(this).val();
              if(typeof arr[index] === undefined)
                arr[index] = [];

             arr[index].push({to:to});  
    });

即使我写arr[index]['from'] = from而不是arr[index].push({from:from});,也会给出错误。

请有人帮我解决这个问题。提前谢谢。

1 个答案:

答案 0 :(得分:1)

如果未定义$nested_collection = Collection { ▼ #items: array:2 [ ▼ 0 => Item { ▼ +id: 1 +first_name: 'first_name 1' +last_name: 'first_name 1' +nbr_hours: 19 } 1 => Item { ▼ +id: 2 +first_name: 'first_name 2' +last_name: 'first_name 2' +nbr_hours: 22 } ] } 处的对象,则需要推送,否则请更新它。您不需要使用index

typeof

&#13;
&#13;
var arr = [];
$('input[name^=from]').each(function(index,val) {
    var from = $(this).val();
    if (arr[index] === undefined) {
        arr[index] = {from: from};
    } else {
        arr[index].from = from;
    }
});
$('input[name^=to]').each(function(index,val) {
    var to= $(this).val();
    if (arr[index] === undefined) {
        arr[index] = {to: to};
    } else {
        arr[index].to = to;
    }
});
&#13;
var arr = [];
$('input[name^=from]').each(function(index, val) {
  var from = $(this).val();
  if (arr[index] === undefined) {
    arr[index] = {
      from: from
    };
  } else {
    arr[index].from = from;
  }
});
$('input[name^=to]').each(function(index, val) {
  var to = $(this).val();
  if (arr[index] === undefined) {
    arr[index] = {
      to: to
    };
  } else {
    arr[index].to = to;
  }
});

console.log(arr);
&#13;
&#13;
&#13;