You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery的each方法处理两个选择器如何生成键值对数组

解决方案

JavaScript 中普通数组是索引为数字的有序集合,你想要的键值对结构建议使用对象或者Map来实现,下面是适配你现有DOM结构的修改方案:

实现代码

HTML结构不变,JS部分修改如下:

function getFields(){
  // 声明对象存储键值对,符合你要的 key=>value 格式
  const windowMap = {};
  // 只遍历所有windowNum输入框,和windowList是一一相邻的对应关系
  $("input[name='windowNum']").each(function() {
    const num = $(this).val().trim();
    // 取当前windowNum的下一个相邻input,就是对应的windowList
    const type = $(this).next("input[name='windowList']").val().trim();
    // 数值不为空时再存储,避免无效键
    if(num) {
      windowMap[num] = type;
    }
  });
  // 输出验证,格式为 {100: 'casement', 200: 'glider'} 符合你的需求
  console.log(windowMap);

  // 如果需要转成数组格式也可以用下面的代码
  // const windowList = Object.entries(windowMap);
  // 输出格式为 [[100,'casement'], [200,'glider']]
}

原代码问题说明

你之前的写法是把windowNum和windowList的所有input放在同一个选择器里遍历,所以会按顺序逐个取到所有值push进数组,自然就是线性的单元素数组,不会形成一一对应的键值关系。

通用适配方案

如果你的DOM结构中两个input不一定是相邻排列的,也可以用索引匹配的写法,只要两组输入框数量一一对应就能正常工作:

function getFields(){
  const windowMap = {};
  const $nums = $("input[name='windowNum']");
  const $types = $("input[name='windowList']");
  $nums.each(function(index) {
    const num = $(this).val().trim();
    const type = $types.eq(index).val().trim();
    if(num) windowMap[num] = type;
  });
  console.log(windowMap);
}

内容的提问来源于stack exchange,提问作者Micha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:39:02