javascript - 如何用jquery制作动态关联数组?

标签 javascript jquery html arrays

我想要这样的数组:-

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

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

。 。 等等。

我有 from 和 to 字段的输入数组 html 元素。

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

现在,我正在从下面的代码创建数组,它在控制台中给我错误,例如“Uncaught TypeError:无法读取未定义的属性'push'”。

    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}); 那么也给出错误。

请大家帮我解决这个问题。提前致谢。

最佳答案

如果 index 处的对象未定义,则需要推送,否则更新它。您不需要使用 typeof

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;
    }
});

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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="from[]" value="1" />
<input type="text" name="to[]" value="1" />
<input type="text" name="from[]" value="2" />
<input type="text" name="to[]" value="2" />

关于javascript - 如何用jquery制作动态关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41184325/

相关文章:

javascript - jQuery - 将动态链接从一个元素复制到另一个元素

Javascript iframe 未在 Bootstrap 弹出窗口中加载(模式)

html - 如何避免在 Bootstrap 多重选择中显示所选选项?

html - 在选项卡中使用选项卡不起作用 - Material Design Lite

javascript - Jquery UI 摇动效果

javascript - 在同一个 Controller nodejs上调用函数

javascript - 验证电子邮件时显示 <div> Jquery

javascript - 如何将焦点放在文本框上?

javascript - 在网站中自定义 Braintree Drop-in UI

javascript - meteor 铁:router transitions